ContentsApplication DesignInterfaces
Previous: What goes where - operational delegation | Next: Collaboration

Interfaces

When we talk about Java from a programming language perspective, interfaces are probably it's best-kept secret. C++ bigots often denigrate Java because it doesn't allow the programmer to inherit from multiple superclasses. There is a good reason for this limitation (to avoid "inheritance diamonds"), but that goes beyond the scope of this tutorial. While Java purposely doesn't provide multiple inheritance for classes, it does provide that capability for interfaces.

An interface is simply a means by which one object can communicate with another. Unlike subclassing - which extends a superclass - interfaces are implemented. If a class implements an interface, it has taken on the obligation of providing methods which are defined in that interface. In OO parlance, this concept is called "polymorphism" - it simply means that "I can use this object in the way described by the interface, even if I don't know anything else about it".

If you got into a car with a blindfold on - and the interior was stripped of any identifying marks - you should be able to drive it when the blindfold is removed. You should be able to do this even though you don't know what kind of car it is, who the vendor is, what version it is, or how it works internally. The reason you can do this is because the car implements an interface that is common between all cars.

To follow the analogy just a bit further, there are two kinds of operator interfaces employed in cars - automatic transmission and standard. These interfaces have different methods for shifting gears. The manual transmission interface requires the use of another method (the clutch pedal) and requires a different use of the shift lever. Even with these differences, there is a large subset of capabilities that are in common between the two interfaces: the steering wheel and brake pedal does the same thing. Consequently, both the automatic and the manual inherit the superclass interface which defines these common methods.

Another part of the car interface is for the turn signal. Here again, there is some variation. In most cases, a lever is provided; but there are some exceptions. Wipers, the same thing. Lights, horn, emergency brake, and so forth. Here's the point: the interfaces can all be inherited without conflict, because these are just methods. The actual, physical, object - the car - may only implement it's attributes (such as diesel or gas engine) once.

Define lots of interfaces, and use them as frequently as you can. The only restriction on them is that they must not define any data.


ContentsApplication DesignInterfaces
Previous: What goes where - operational delegation | Next: Collaboration