• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Interface question

 
Gary Ba
Ranch Hand
Posts: 161
Firefox Browser Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?

Thanks,
Gary
 
Katrina Owen
Sheriff
Posts: 1367
18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm not sure what you mean by "assign" here.

Do you mean

TheInterface something = new SomeClass();

?
 
Gary Ba
Ranch Hand
Posts: 161
Firefox Browser Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes.

I came across where if I have..

Map<> map = new HashMap<>() is preferred over

HashMap<> map = new HashMap<>().

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?
 
Katrina Owen
Sheriff
Posts: 1367
18
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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".
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic