我有一个抽象 class w/ 1 setter 方法 - 参数是一个对象。我想要一个通用的 <T> 参数,它采用扩展它的 class 的类型

I have an abstract class w/ 1 setter method - parameter is an object. I want a generic <T> parameter that takes on the type of the class extending it

我想要的:

而不是 "public void insertDog(Object object)" 方法中的 "Object",我想要一个扩展 class 扩展抽象 class "DogKennel." 的泛型 例如,如果我创建了一个名为 "RetrieverDogKennel" 的 class,它扩展了 "DogKennel," 我希望 "RetrieverDogKennel" class 的 "insertDog(...)" 方法中的参数只接受 "Retriever" 对象。虽然它看起来不像这样 "insertDog(Retriever retriever)" 该方法会像它一样工作,只允许在其参数中使用检索器对象。

public abstract class DogKennel
{

   public void insertDog(Object object)
   {

   //does something and the object is not stored

   }

}

public class RetrieverDogKennel extends DogKennel
{

   public <T extends Retriever> void insertDog(T object)
   {

   //does something and the object is not stored

   }

}

如果您尝试将其他犬种放入 RetrieverDogKennel,我希望它是一个错误。

LabradorDogKennel labradorDogKennel = new LabradorDogKennel();
RetrieverDogKennel retrieverDogKennel = new LabradorDogKennel();

Labrador bullet = new Labrador(); 
Retriever buster = new Retriever();
Retriever sparky = new Retriever();



//No Error
retrieverDogKennel.insertDog(buster);

//Error
retrieverDogKennel.insertDog(bullet);

已更新

您需要使两个 classes 通用,而不是 subclass 方法:

public interface Dog {
}

public class Labrador implements Dog
{
}

public abstract class DogKennel<T extends Dog> {

    public void insertDog(T dog) {
        //does something and the dog is not stored
    }

}

public final class RetrieverDogKennel extends DogKennel<Retriever> {
}

public final class GeneralDogKennel extends DogKennel<Dog> {
}

使用该代码,RetrieverDogKennel class 有一个 insertDog(Retriever dog) 方法,其实现继承自基础 class。

GeneralDogKennel class 有一个 insertDog(Dog dog) 方法,即它会接受任何类型的狗。