File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Cattle Drive and the fly likes Interface question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » This Site » Cattle Drive
Bookmark "Interface question" Watch "Interface question" New topic
Author

Interface question

Gary Ba
Ranch Hand

Joined: Oct 23, 2009
Posts: 150

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


star chaser..
Katrina Owen
Sheriff

Joined: Nov 03, 2006
Posts: 1344
    
  12
I'm not sure what you mean by "assign" here.

Do you mean

TheInterface something = new SomeClass();

?
Gary Ba
Ranch Hand

Joined: Oct 23, 2009
Posts: 150

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

Joined: Nov 03, 2006
Posts: 1344
    
  12
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".
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Interface question
 
Similar Threads
Map mock question
String as key to look up an Integer
Map<Integer,Integer> or Map<String,String>
LinkedHasMap Question
Populating HashMaps of HashMap of Objects