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

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

    The reason why you may want to do this is to create more robust designs. Take for example the Collections Framework in Java. You have a List interface and then you have two implementations, ArrayList and LinkedList.

    You can write your program to use a LinkedList specifically or an ArrayList specifically. However, your program then depends on those specific implementations.

    If you write your program to depend on the super type, List, instead then your program can work for either of the List implementations. Lets say you want to write a method that does something to a List and you wrote this:

      public void doSomething(ArrayList a){}
    

    This method can only be called with an ArrayList, not a LinkedList. Suppose that you wanted to do the same thing with a LinkedList? Do you then duplicate your code? No.

      public void doSomething(List l){}
    

    Will be able to accept either type of List.

    The principle behind this is program to an interface not an implementation. That is, List defines the functions of ALL lists.

    There are many many examples of this usage.

提交回复
热议问题