Java Reference
In-Depth Information
CHALLENGE 2.3
Give an example of an interface with methods that do not imply responsibility on
the part of the implementing class to take action on behalf of the caller or to return
a value.
If you create an interface that specifies a collection of notification methods, you should
consider also supplying a
stub
—a class that implements the interface with methods that do
nothing. Developers can subclass the stub, overriding only those methods in the interface that
are important to their application. The
WindowAdapter
class in
java.awt.event
is
an example of such a class, as Figure 2.1 shows. (For a whirlwind introduction to UML, see
Appendix C, UML at a Glance, on page 441.) The
WindowAdapter
class implements all
the methods in the
WindowListener
interface, but the implementations are all empty;
the methods contain no statements.
Figure 2.1. The
WindowAdapter
class makes it easy to register for window events while
ignoring any events you are not interested in.
CHALLENGE 2.4
What is the value of a stub class like
WindowAdapter
, composed of methods that
do nothing? (Writing out your answer will give you practice at refining and
articulating your position.)
Placing Constants in Interfaces
Interfaces and classes can also cooperate when it comes to defining constants. A
constant
is a
field that is static and final.