posted 18 years ago
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