Objects and Classes in Java |
An 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
mousePressed
method, for a class to be notified when the user releases the mouse button it must have amouseReleased
method, and so on. This protocol is codified in theMouseListener
interface, which declares these five methods, one for each type of mouse event: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
implements
clause in the class declaration. Your class can implement more than one interface (Java supports multiple interface inheritance), so theimplements
keyword is followed by a comma-delimited list of the interfaces implemented by the class.
Spot
, which displays a spot where the user presses the mouse button, needs to know about mouse pressed events (the event when the mouse button is initially pressed down) in order to function. Therefore,Spot
must implement theMouseListener
interface:class Spot extends Applet implements MouseListener { . . . }
By Convention: Theimplements
clause follows theextends
clause, if it exists.
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
Spot
must implement all five ofMouseListener
's methods:Note that the last four methods have empty implementations. This is becausepublic void mousePressed(MouseEvent event) { clickPoint = event.getPoint(); repaint(); } public void mouseClicked(MouseEvent event) {} public void mouseReleased(MouseEvent event) {} public void mouseEntered(MouseEvent event) {} public void mouseExited(MouseEvent event) {}Spot
is interested only in "mouse pressed" events. When the user presses the mouse button,Spot
displays a spot where the click occurred. However, becauseSpot
is declared to implement theMouseListener
interface andMouseListener
declares five methods,Spot
must implement them all. You can use inner classes in conjunction with severaljava.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.
Objects and Classes in Java |