Why do we use interface reference to a child object?
For example :
Map m = new HashMap();
why?
Instead we can use
HashMap hm = new HashMap();
Why do we use interface reference to a child object?
For example :
Map m = new HashMap();
why?
Instead we can use
HashMap hm = new HashMap();
You can later change it to some other class's object. For example,
Map m = new HashMap();
m = new TreeMap();
This way you can easily change the implementation at any time.
Second point to be noted is, by using interface reference you can call only those methods of child class that are declared in interface.
You will not be able to call those methods of child class which are not declared in the interface and hence are not overridden methods.
From Joshua Bloch's, Effective Java, he says that it is better, if possible, to refer objects by their interfaces. This will give your program more flexibility down the road, and if you decide you want to switch implementations, all you will need to do is change the class name in the constructor. Reasons to change implementations might be better performance or extra functionality.
// favorable
List users = new Vector();
// dont do this if possible
Vector users = new Vector();
It is completely fine to refer to object by class instead of interface if there is no interface that exists for it.