你的问题的根源是一个类设计问题:你试图从一个具体的类继承,这几乎总是一个错误,并且(你的例子)必然会导致许多问题.要坚持参考线程中给出的例子,你不应该实例化狗,因为在这样的宇宙中,一般不存在狗,只有宠物 – 只有贵宾犬,纽芬兰,西班牙人等.因此,getThis不应该是在中级(抽象)类中实现,仅在(具体)叶类中实现.在所有中级抽象类中,您应该只引用泛型类型参数T,而不是实际的类名.
public class TestClass {
static abstract class Pet > {
private String name;
protected abstract T getThis();
public T setName(String name) {
this.name = name;
return getThis(); }
}
static class Cat extends Pet {
@Override protected Cat getThis() { return this; }
public Cat catchMice() {
System.out.println("I caught a mouse!");
return getThis();
}
}
// Dog is abstract - only concrete dog breeds can be instantiated
static abstract class Dog> extends Pet {
// getThis is not implemented here - only in concrete subclasses
// Return the concrete dog breed, not Dog in general
public T catchFrisbee() {
System.out.println("I caught a frisbee!");
return getThis();
}
}
static class Poodle extends Dog {
@Override protected Poodle getThis() { return this; }
public Poodle sleep() {
System.out.println("I am sleeping!");
return getThis();
}
}
static class NewFoundland extends Dog {
@Override protected NewFoundland getThis() { return this; }
public NewFoundland swim() {
System.out.println("I am swimming!");
return getThis();
}
}
public static void main(String[] args) {
Cat c = new Cat();
c.setName("Morris").catchMice();
Poodle d = new Poodle();
d.setName("Snoopy").catchFrisbee().sleep();
NewFoundland f = new NewFoundland();
f.setName("Snoopy").swim().catchFrisbee();
}
}