We use interface references to Collections. Is it only for the good coding practice or have some logic behind it? Can anyone explain?
For example:
We use
Map<String, Integer> map = new HashMap<String,Integer>();
Instead of
HashMap<String, Integer> map = new HashMap<String,Integer>();
Having
interfacewill allow you to change the implementation in future transparently (Without many changes on client side).For example:
Even though you change implementation to LinkedHashMap, client don’t need to make any changes on their end.
If you use
Client is tightly coupled with implementation. If you change implementation, then you need to change client also.
One draw back would be, If you would like to use any implementation specific methods, you need to cast to the corresponding type and use it.