Why the coding should be “to the interface” especi

2019-09-02 10:48发布

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.

6条回答
我命由我不由天
2楼-- · 2019-09-02 11:18

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.

查看更多
地球回转人心会变
3楼-- · 2019-09-02 11:19

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.

查看更多
虎瘦雄心在
4楼-- · 2019-09-02 11:20

Because mymap can be instantiated somewhere else with a different implementation of Map, you should not rely on it being an instance of HashMap in the code using it.

查看更多
闹够了就滚
5楼-- · 2019-09-02 11:20

The former allows you to change to:

Map<Integer, String> mymap = new TreeMap<Integer, String>(); 

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.

查看更多
在下西门庆
6楼-- · 2019-09-02 11:31

Using Map mymap allows you to change the implementation later. For example, if at some point you need mymap to be ordered, you just change the initialization to LinkedHashMap.

查看更多
在下西门庆
7楼-- · 2019-09-02 11:38

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.

查看更多
登录 后发表回答