Possible Duplicate:
Why are variables declared with their interface name in Java?
How should lists be cast to their conrecte implementations?
Example:
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
Thanks.
Possible Duplicate:
Why are variables declared with their interface name in Java?
How should lists be cast to their conrecte implementations?
Example:
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
Thanks.
This is usually so that you can swap in another implementation later and still have the code operate the same. For example, if you then decided to use a TreeMap
instead of a HashMap
, you could just change the instantiation step, and the rest of your code would still work just fine.
You could switch implementations (e.g. in your example switch to a TreeMap
) without affecting the rest of the code, since it will use the base class i.e. Map
.
It decouples your code and is considered a good programming practice to code against an interface instead of a concrete implementation
Design by Contract or "Programming to an Interface" are principles that ensure that your code only uses the properties/methods exposed by the interface, and more importantly, one primary interface at any given time. If you're using multiple interfaces at a time, that is generally a sign of tighter coupling.
In general, you should not instantiate objects directly in your code either. You should delegate that job to an external entity so that any changes of the implementation used, can be done in a single place.
There was a Dr Dobb's Journal article that the 'new' keyword should be forbidden (exact title was something like 'new is verboten') but I can't find a link to it right now.