Java – Is it possible to create instance of an Interface(e.g-Map Interface)?If it is then how

javamap

In most Java code, I see people declare Java objects like this:

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

instead of:

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

How is it possible (i know it is but why) to create instance of a Map interface when we know that we can't create instance of an interface.Please explain.
Thanks in advance.

Best Answer

It's called polymorphism:
The instance of a class can be treated as instance of that class but also as an instance of every interface the class implements, since it has to implement all the interface's methods. An interface is a contract that says: "The class implementing me offers at least the same operations that I offer."

Every HashMap is a Map, but not every Map is a HashMap.

Related Topic