Way to make Java parent class method return object of child class

What are you trying to achieve ? It sounds like a bad idea. A parent class should not know anything about its children. It seems awfully close to breaking the Liskov Substitution Principle. My feeling is that your use case would be better serve by changing the general design, but hard to say without more informations.

Sorry to sound a bit pedantic, but I get a bit scared when I read such question.


You can call this.getClass() to get the runtime class.

However, this is not necessarily the class that called the method (it could be even further down the hierarchy).

And you would need to use reflection to create new instances, which is tricky, because you do not know what kind of constructors the child class has.

return this.getClass().newInstance(); // sometimes works

Simply to demonstrate:

public Animal myMethod(){
  if(this isinstanceof Animal){
     return new Animal();
  }
  else{

     return this.getClass().newInstance();
  }
}

If you're just looking for method chaining against a defined subclass, then the following should work:

public class Parent<T> {

  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<ChildA> {

  public ChildA childAMethod() {
    System.out.println(this.getClass().getCanonicalName());
    return this;
  }
}

public class ChildB extends Parent<ChildB> {

  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

Tags:

Java

Generics