One solution is to override the method in the child class and change the return type to a more specific one, i.e. type of child. This requires casting. Instead of using a typical cast (Child) use the Class#cast(Object) method
public class Parent { public Parent example() { System.out.println(this.getClass().getCanonicalName()); return this; } } public class Child extends Parent { public Child example() { return Child.class.cast(super.example()); } public Child method() { return this; } }
Casting is hidden in the standard method. From source Class .
public T cast(Object obj) { if (obj != null && !isInstance(obj)) throw new ClassCastException(cannotCastMsg(obj)); return (T) obj; }
Sotirios delimanolis
source share