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.
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.
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.
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.