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

后端 未结 6 1746
后悔当初
后悔当初 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:17

    Inheritance and Polymorphism are cornerstones of object-oriented programming and serve a few different purposes, in short:

    • Code reuse by extending a base class with specific functionality,
    • Interface design by providing an abstract set of functionality, which where different implementations are tailored to different requirements and
    • Encapsulation by hiding specific functionality, which isn't needed in certain contexts

    among others.

    The last point also highlights, why one might use a restricted set of functionality, even in a case the actual implementation provides more than that. Take for example the Collection interface. By using this interface, we focus on methods like isEmpty, contains or size but not the actual implementation.

提交回复
热议问题