Is there any elegant way to make Java method located within parent class return object of child class, when this method is called from child class object?
I want to
If you're just looking for method chaining against a defined subclass, then the following should work:
public class Parent {
public T example() {
System.out.println(this.getClass().getCanonicalName());
return (T)this;
}
}
which could be abstract if you like, then some child objects that specify the generic return type (this means that you can't access childBMethod from ChildA):
public class ChildA extends Parent {
public ChildA childAMethod() {
System.out.println(this.getClass().getCanonicalName());
return this;
}
}
public class ChildB extends Parent {
public ChildB childBMethod() {
return this;
}
}
and then you use it like this
public class Main {
public static void main(String[] args) {
ChildA childA = new ChildA();
ChildB childB = new ChildB();
childA.example().childAMethod().example();
childB.example().childBMethod().example();
}
}
the output will be
org.example.inheritance.ChildA
org.example.inheritance.ChildA
org.example.inheritance.ChildA
org.example.inheritance.ChildB
org.example.inheritance.ChildB