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

后端 未结 7 487
北海茫月
北海茫月 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:29

    public class Parent {
        public Parent myMethod(){
            return this;
        }
    }
    public class Child extends Parent {}
    

    And invoke it like

           Parent c = (new Child()).myMethod();
           System.out.println(c.getClass());
    

    Is this solution is correct? If it is, then, how is it different from the #1 solution?

提交回复
热议问题