Java – why reference the base class when I can access all methods by referencing subclasses?
I'm learning java concepts
Anyone can give me the actual concept. Why do we have to assign subclass instances to base class references? What needs to be done? Instead, we can refer from subclasses only to those base class functions
It is explained by considering specific base classes and many subclasses in the hierarchy
Solution
The reason you might want to do this is to create a more powerful design Take the Collections Framework in Java as an example You have a list interface, and then you have two implementations, ArrayList and LinkedList
You can write programs to specifically use LinkedList or ArrayList However, your program depends on these specific implementations
If your program depends on the supertype list, your program can be applied to any list implementation Suppose you want to write a method to perform some operations on the list, and you write this:
public void doSomething(ArrayList a){}
This method can only be called with ArrayList, not LinkedList Suppose you want to do the same thing with LinkedList? Do you copy your code? No,
public void doSomething(List l){}
Will be able to accept any type of list
The principle behind this is the program of the interface, not the implementation In other words, list defines the function of all list
There are many examples of this usage