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

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

    Simply to demonstrate:

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

提交回复
热议问题