Java Reference
In-Depth Information
Chapter 2. Introducing Interfaces
Speaking abstractly, a class's interface is the collection of methods and fields that a class
permits objects of other classes to access. This interface usually represents a commitment that
the methods will perform the operation implied by their names and as specified by code
comments and other documentation. A class's implementation is the code that lies within its
methods.
Java elevates the notion of interface to be a separate construct, expressly separating
interface—what an object must do—from implementation—how an object fulfills this
commitment. Java interfaces allow several classes to provide the same functionality, and they
open the possibility that a class can implement more than one interface.
The Java interface construct is a powerful tool worth studying in its own right, but your
design intent will sometimes go beyond the simple definition of an interface. For example,
you might use an interface to adapt a class's interface to meet a client's needs, applying the
A DAPTER pattern. You might also create an interface to a collection of classes, applying the
F ACADE pattern. In this case, you create a new interface by creating a new class rather than a
new interface. In these circumstances and others you can apply design patterns to go beyond
the ordinary use of interfaces.
Ordinary Interfaces
Design Patterns (Gamma et al. 1990) frequently mentions the use of abstract classes but does
not describe the use of interfaces. The reason is that the languages C++ and Smalltalk, which
Design Patterns uses for its examples, do not have an interface construct. This omission has a
minor impact on the utility of the topic for Java developers, because Java interfaces are quite
similar to abstract classes.
CHALLENGE 2.1
Write down three differences between abstract classes and interfaces in Java.
The basic definition of Java interfaces is not complex. However, you should be aware of a
few subtle points when using them.
Consider the definition of an Oozinoz interface that rocket simulation classes must
implement. Engineers design many different rockets, including solid- and liquid-fueled
rockets, with completely different ballistics. Regardless of how a rocket is composed, a
simulation for the rocket must provide figures for the rocket's expected thrust and apogee , or
the greatest height the rocket will achieve. Here is the exact code, minus the code comments,
that Oozinoz uses to define the rocket simulation interface:
Search WWH ::




Custom Search