Java Reference
In-Depth Information
Implementing an Interface
When a class implements an interface, you can think of the class as signing a
contract, agreeing to perform the specific behaviors of the interface. If a class
does not perform all the behaviors of the interface, the class must declare itself
as abstract.
More specifically, when a class implements an interface, the class has two
options:
Implement all of the methods in the interface
■■
Be declared as abstract
■■
A class uses the implements keyword to implement an interface. The imple-
ments keyword appears in the class declaration following the extends portion
of the declaration. The format for implements looks similar to:
public class ClassName extends ParentClassName implements InterfaceName
For example, the following HelloWorld class declares that it implements the
Runnable interface:
public class HelloWorld implements Runnable
The HelloWorld class is not declared as abstract, so it must contain the run()
method declared in the Runnable interface.
A class can implement more than one interface, in which case a comma is
used to separate the multiple interfaces. For example, the following Hel-
loWorld class implements both the Runnable interface and the
java.awt.event.MouseListener interface:
public class HelloWorld implements Runnable,
java.awt.event.MouseListener
Again, because HelloWorld is not abstract, it must contain the run() method
declared in the Runnable interface and the five methods declared in the
MouseListener interface.
Now that we have seen the implements keyword, write a class that imple-
ments our Paintable interface written in the previous section.
Write a Class That Implements Paintable
In this step, we will write a class named Rectangle that implements the
Paintable interface. Open your text editor, and type in the class shown in
Figure 10.3.
Search WWH ::




Custom Search