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

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

    Polymorphism.

    I am a method that gives you a List. All you need to know about the thing I've actually given you is that it's a list and has the behaviour and semantics of a list, i.e. you can put things in it, it'll maintain their ordering, and you can iterate over it.

    What you don't need to know is how I'm storing things, how I'm making them accessible, etc. That's not important. For all you care, it could be a LinkedList, an ArrayList or something entirely new. Suffice it to say, I've picked something, and you can happily use it.

    You're absolutely right that when you're using inheritance to extend classes and add new behaviour, then you need to reference the subclass to be able to access it. The two approaches are somewhat complimentary, but different, use cases.

提交回复
热议问题