Java Reference
In-Depth Information
Java syntax: Implements clause
implements
interface-name
,
…
,
interface-name
Example
:
implements
I, Comparable
Purpose
: Placing this implements clause in a class header indicates that
the class implements all the methods of interfaces
I
and
Comparable
.
public class
C1
implements
ActionListener {
void
actionPerformed(ActionEvent b)
{
code in method body
}
}
The presence of the clause
implements
ActionListener
forces class
C1
to pro-
vide an implementation of the methods described in interface
ActionListener
;
otherwise, the class definition is syntactically illegal.
12.1.1
The interface as a type
We just showed how a class could implement an interface. We now go into more
detail about what this means. We show that an interface can be the type of a vari-
able, and we discuss the ramifications of an interface being a type. The follow-
ing two sections contain case studies that use interfaces, and you might want to
peruse them in between studying parts of this section.
Figure 12.1 contains an interface
I
and two classes
F
and
G
. We use short
names for the interface and its methods in order to keep diagrams and text man-
ageable. The names are not important to our goal in this section.
To the left in Fig. 12.2 is an object
a0
of class
G
, with the partition for class
G
at the bottom, then the partition for class
F
, and above that the partition for class
Object
. A variable
ob
contains the name
a0
.
We want to show how the implementation of interface
I
within class
G
affects the object. To do this most effectively, we replace the lines separating the
components of subclasses by arrows and remove the box around the object —we
Activity
12-2.1
interface
I {
void
p(C e);
}
public class
F { }
public class
G
extends
F
implements
I {
Button b;
public
G() { ... }
void
p(C e) { ... }
}
Figure 12.1:
Interface
I
and classes
F
and
G
Search WWH ::
Custom Search