Possible Duplicate:
What does it mean to “program to an interface”?
I noticed that some people like to declare an object as one of the interfaces it implements even though, within the scope of the variable, it is not necessary to look at it as the interface, e.g. there is no external API that expect an interface.
For example:
Map<String, Object> someMap = new HashMap<String, Object>();
Or you can just do
HashMap<String, Object> someMap = new HashMap<String, Object>();
and avoid importing java.util.Map
altogether.
What are the advantages of declaring it through an interface (first above) as opposed to the class itself (second above)?
Thanks
An interface such as Map<A, B>
declares what an object can do. On the other hand, a class such as HashMap<A, B>
defines how an object does what the interface declares it does.
If you declare a variable (or field, or whatever) a Map<A, B>
, you are stating that your code depends only on the contract defined by that interface, it does not depend on the specifics of an implementation.
If you declare it a HashMap<A, B>
, it is to be understood that you need that specific version of a map (for whatever reason), and it cannot be replaced for something else.
I tend to dislike the common answers like "because you can change the implementation" simply because, after years and years of practice, you will see that it won't happen as frequently as that, and the major benefits are really this subtle (but clear) expression of your intents.
Since it's not part of API, it is implementation detail. It's better to be specific in implementations, there's no point to be abstract here.
my prev answer
Use interface or type for variable definition in java?
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