Why in Java, we need to create Reference of Parent Class and Object of Sub class? What do we achieve with this? Obvious answer is Polymorphism, but then what is the scope? How does it help in real time?
I came across this while learning java.
Why in Java, we need to create Reference of Parent Class and Object of
Share
In your example, by using a parent class reference, you can write a method that takes any kind of List and operates on it, without caring about the specific type of list that it is being passed.
On the other hand, the subclass specifies the actual implementation, so the user of the method can choose whatever list is most efficient or appropriate for his requirement.
Suppose you write a method that computes the sum of a List:
Now suppose one user of your method has a list in which he cares about fast random access, so he creates an ArrayList, while another user wants to frequently splice and join his lists, so he uses a LinkedList instead.
Both these users can now use your sum method.