I have a doubt on the design methodology that why we implement the code to the interface. This is very much observed in primitive data types. Like I am not getting the difference between these two :
Map<Integer, String> mymap = new HashMap<Integer, String>();
And
HashMap<Integer, String> mymap = new HashMap<Integer, String>();
Is there any difference between these two? I mean each and every place where we are going to use mymap
will remain same in both the cases.
I am sorry if the question seems to be of no use but I really not getting that how this is going to make any difference later on where mymap
will be used. Please help?
Thanks..
Note - I have already seen this question on SO but it is not giving what I want.
In the specific instance you propose, it may not make a difference, but it's good practice to get yourself used to always use the interface in your declarations because there are legitimate instances where you will need that flexibility.
If you are only using this inside your type (meaning: private) and instantiate it yourself, it doesn't make a real difference.
It starts getting interesting if the public interface of your type exposes a Map vs. a HashMap.
Because mymap can be instantiated somewhere else with a different implementation of
Map
, you should not rely on it being an instance ofHashMap
in the code using it.The former allows you to change to:
for example, without breaking all the rest of your code.
A much more minor advantage is that your IDE can show you the methods for the interface, rather than the (potentially much larger number of) methods for the implementation.
Using
Map mymap
allows you to change the implementation later. For example, if at some point you needmymap
to be ordered, you just change the initialization toLinkedHashMap
.The second option limits you to always use HashMap, even if some day TreeMap could be more useful.
In the first one you can change the particular implementation easier - you only have to change one line of code. It's especially visible if you return your map from methods - the method return type doesn't have to change.
Coding to an interface also helps mocking the object during tests, but I assume that's not the case here.