This week's book giveaways are in the iOS and Features new in Java 8 forums. We're giving away four copies each of Barcodes with iOS: Bringing together the digital and physical worlds and Core Java for the Impatient and have the authors on-line! See this thread and this one for details.
The rule is to program to an interface and not the implementations which in
this case the interface is a Map and the implementation is a HashMap. For example,
Map<String, Integer> names = new HashMap<String, Integer>();
Here is another question that confuses me. If I create a Class that implements anInterface, does this mean I need to assign the created Class to an Interface? Or this rule only applies to existing Collections?
So my question is if I have a Class that implements AnotherClass, is it in good practice to do the same.
AnotherClass name = new Classname();
If not, what are the cases/examples where you prefer one from the other?
Joined: Nov 03, 2006
It really depends.
Let's say you have a Car class that implements Fuelable. In some cases you want to be dealing with the car, and it makes no sense to operate at the fuelable level. But if you are writing the FuelingStation you may not want to worry about whether or not you are dealing with a Car or a Motorhome or a Motorcycle or even a FlyingContraptionInventedByYourBrother. All you want to know is whether or not it can take fuel.
The maxim about "program to an interface not to an implementation" doesn't necessarily mean java Interface vs java Class. To simplify somewhat: "make sure your stuff is talking to each other in the best way that makes sense, and that they don't have to worry about incidental details".