posted 22 years ago
This is known as the "program to the interface, not to the implementation" rule. The advantage is to swap your object implementations without affecting the code where this object is used. For example, if you have code like this:
The way it is coded, the caller of that method must pass an instance of a HashMap to it, otherwise the compiler will generate an error. Now, suppose that you have 100 methods like this, and you decided not to use a HashMap anymore, but a TreeMap (for optimization purposes). You now must change your code in 100 different places.
Now compare it with this code:
Notice that if you want to replace your HashMap with a TreeMap, you only need to make a change in only one place, where a map is instantiated.
Isn't this beautiful?