0

I might sound dumb asking this question or internet would have lot of reference about this question. But trust me I din't find any answer that answer properly. So I decided to ask this question

So here is why do we declare object this way eg Map m = new HashMap() why not HashMap m = new HashMap()

in general why we declare object of superclass type that reference to subclass object.

Naushad Ahmad
  • 476
  • 5
  • 22

1 Answers1

-1

Well, this let you to change the implementation without to relay on a specific class.

Please consider just the example you've done, we prefer to use

Map<String, String> m2 = new HashMap<>();

over

HashMap<String, String> m2 = new HashMap<>();

This let you the freedom to choose another implementation which could be more performing.

Map<String, String> m2 = new TreeMap<>();
freedev
  • 25,946
  • 8
  • 108
  • 125
  • Could I have a comment for this down vote? – freedev Apr 03 '17 at 11:51
  • Can I have a comment why you answer obvious duplicates? – Tom Apr 03 '17 at 11:51
  • Sorry but I don't get what's wrong with this answer even if it is duplicate. I see a lot of duplicate answers that are upvoted when they are pertinent. And when I was writing my answer I didn't even know that it was duplicated. – freedev Apr 03 '17 at 11:53
  • Duplicates shouldn't be answered, this just spreads knowledge and makes it way harder to maintain that knowledge. *"I see a lot of duplicate answers that are upvoted when they are pertinent"* Yes, that's a flow with many SO users who don't know what the purpose of this site is. So if you feel that your answer is important/helpful, then post it in one of the linked questions above, but not here. Thank you. – Tom Apr 03 '17 at 11:56
  • I could agree, but it let you practically impossible write an answer without to incur in a down vote, if someone found that is duplicate. – freedev Apr 03 '17 at 11:58
  • Or you search for a dupe first ... And no worries, there are just a few users who actually care about the quality of this site, so a DV for posting obivous dupes is quite rare. – Tom Apr 03 '17 at 11:59
  • I think that the fact that it is not possible add new answers when the question is marked as duplicated is enough. You should not oppress who write an answer, my opinion though. – freedev Apr 03 '17 at 12:01
  • You can write answers wherever you want, but I'm not obligated to appreciate that. – Tom Apr 03 '17 at 12:03
  • 1
    argh... :) touche – freedev Apr 03 '17 at 12:04