This week's book giveaway is in the OCPJP forum. We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line! See this thread for details.
Statement: You can store the reference to any object instantiated from any class that implements an interface in a reference variable of that interface type. I understand that I can do it. What I would like to know is why would I want to do it. What is the advantage to using an interface reference instead of an object one?
Well, for instance, Collection, Set, List and Map are all interfaces. You might want to work with the methods promised by one of those interfaces, and not care about the exact class that is providing those behaviors. This allows you to write programs depending on the important abstractions rather than the concrete details.
Declaring a variable or parameter to match an interface type allows you to use a variety of classes that implement that interface now and in the future. For example if we write a method like:
then we can pass in any object that implements Set: HashSet, TreeSet, LinkedHashSet, or any other new Sets that come down the road one day. The getSum method can only call the methods defined for Set, none of the special methods added by the various implementing classes, but we can do computeSum with just those methods. Here's another cute trick with collections. Populate a collection that is efficient for "put" then sort it into another collection.
To get a bit more advanced, we can use interfaces to manage dependencies between packages. For example, we'd like a Panel to depend on a Customer object and not the other way around. And we'd like the Customer to send a message to the Panel when data changes. How can we code the Customer without making the Customer know something about a Panel method that it can call? In the Customer package, we define an interface which interested parties must implement to be notified. The Panel can implement the interface - creating the appropriate dependency on the Customer - and register itself with the Customer to receive messages. Lemme know if that helps! [ June 30, 2003: Message edited by: Stan James ]
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi