Why should I reference the base class when I can access all the methods just as well by referencing the subclass?

后端 未结 6 1712
后悔当初
后悔当初 2021-01-20 14:32

I am learning java concepts. I got a doubt in java inheritance concept. In inheritance we can assign subclass instance to a base class reference and with that we can access

6条回答
  •  北恋
    北恋 (楼主)
    2021-01-20 15:22

    There is no real need to do that, except when the API demands it. For example, if in a particular API or code library there is a

    void ReallyUsefulFunction(BaseClass instance)
    

    that you would like to use, you can derive a class fom BaseClass and implement its methods in the SubClass. Then you can now pass the subclass to the function.

    Still, technically, you could implement your own

    void MyReallyUsefulFunction(MyClass instance)
    

    which imitates the same functionality. But like what MYYM had explained, the benefits of code reuse etc. can be huge, and that is when you will want to take advantage of polymorphism.

提交回复
热议问题