It is impossible in the Java type system for Parent
to refer to the exact class of this
. However, it can have a type parameter (say T
) that subclasses can specify, as either themselves, or some other type (whatever they want), and use an abstract method to delegate the task of obtaining an instance of a that type T
to the subclass.
public abstract class Parent<T> {
// the implementer is responsible for how to get an instance of T
public abstract T getT();
// in this case, foo() is kind of redundant
public T foo() {
return getT();
}
}
public class Child extends Parent<Child> {
public Child getT() {
return this;
}
public void childMethod() {
System.out.println("childMethod called");
}
}
Child child = new Child();
child.foo().childMethod(); // compiles