|
|
|
|||
|
Implementing an InterfaceAn interface defines a protocol of behavior. A class that implements an interface adheres to the protocol defined by that interface. Let's look at theSpot class to get a better idea of what this means.
To get mouse events from the AWT, the AWT requires a class to adhere to
a certain protocol. For example, for a class to be notified by the AWT
when the user presses a mouse button, the class must have a
Any class interested in getting mouse events must adhere to the protocol. It does this by implementing themouseClicked(MouseEvent) mouseEntered(MouseEvent) mouseExited(MouseEvent) mousePressed(MouseEvent) mouseReleased(MouseEvent) MouseListener
interface.
To declare a class that implements an interface,
include an
When a class declares that it implements an interface, it's basically
signing a contract to the effect that it will provide implementations
for all of the methods in the interface. So
Note that the last four methods have empty implementations. This is
because Spot is interested only in "mouse pressed" events.
When the user presses the mouse button, Spot
displays a spot where the click
occurred. However, because Spot is declared to implement the
MouseListener interface and MouseListener
declares five methods, Spot
must implement them all. You can use inner classes in conjunction with
several java.awt.event "adapter classes" to avoid writing empty
methods. The next section shows you how.
For a complete discussion about interfaces, what they're for, and how to write them, go to Creating Interfaces in the next lesson. | |||
|