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

后端 未结 7 460
北海茫月
北海茫月 2020-12-04 22:23

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

7条回答
  •  有刺的猬
    2020-12-04 22:31

    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
    

提交回复
热议问题