Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

interface vs class

Status
Not open for further replies.

kanghao

IS-IT--Management
Jul 4, 2004
68
KR
When I use "Map map = new HashMap();"
instead of "HashMap map = new HashMap();",
what's the advantage over the latter?
 
If you declare your instance variable of type 'Map', you'll be using it in the rest of the code in a manner consistent with the Map interface. Therefore, if you wish at some later date to swap out the use of the HashMap implementation of Map for a more appropriate one, this can be done by simply changing your 'Map map = new HashMap();' line. Perhaps a TreeMap would be better for your code? Simple; change that line to be 'Map map = new TreeMap();'. Job done!

If you had used 'HashMap map = ..' instead, you'd be in danger of using any unique methods HashMap offers, so locking your code to this implementation.

Tim
 
All of timw's comments are correct, however, in the real world, perhaps Map is not the best example of why you would work with interfaces. I always prefer to look at the java.sql.Connection class as a marvellous example of why interface use makes sense.

In JDBC, the java.sql.Connection interface class is the main object that you work with when connecting to databases. Now,, each database required vendor specific protocols and code, and it would be impossible for JDBC to work without an interface.

Because to be JDBC compliant, a database driver vendor must implement java.sql.Connection (ie make a concrete class that implements an interface), it means that whatever database you are working with, all JDBC client code will look the same, because they use interfaces rather than concrete classes to describe the API. Its up to individual vendors to create their own product-specific code that implements the nterface.

Hope this was clear ?!



Click here to learn Ways to help with Tsunami Relief
--------------------------------------------------
Free Database Connection Pooling Software
 
Yes, that's a good clear example, IMO.

Kanghao, it might be worth giving the 'Object-Oriented Analysis & Design' forum a visit. Also have a read of some 'OO Design Patterns' for examples of the things interfaces make possible. A Google search should yield plenty of material.

Tim.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top