Possible Duplicate:
Why should the interface for a Java class be prefered?
What is the benefit of polymorphism using Collection interface to create ArrayList object?
I see in many examples that when one creates an instance of some collection like TreMap, he uses it's base as type:
Map<String,String> theMap = new TreeMap<String,String>();
Why not to use
TreeMap<String,String> theMap = new TreeMap<String,String>();
Because it's considered a better practice to code to the interface (Map) instead of the implementation (TreeMap). This way you are free to switch to a different implementation (e.g. HashMap, if you later decide it is a better solution) with minimal code touch-points.
It's generally better to code to an interface, not an implementation, which allows an implementation change without having to change code that refers to it.
The only time it's reasonable to not do this is when code relies on characteristics of a specific implementation. For example, if the code requires the fast indexed list item access ArrayList
provides, it might make sense to force a specific implementation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With