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

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

    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
    
    0 讨论(0)
提交回复
热议问题