Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the benefits of declaring an object as interface? [duplicate]

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

like image 497
amphibient Avatar asked Oct 09 '12 17:10

amphibient


2 Answers

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.

like image 111
Bruno Reis Avatar answered Nov 10 '22 10:11

Bruno Reis


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?

like image 39
irreputable Avatar answered Nov 10 '22 08:11

irreputable