Java Reference
In-Depth Information
the anonymous class in this example is almost too long—that is why we replaced
the body with <
body of class
> when explaining the creation of the anonymous
class. In this fashion, you could see how simple it is to make a local inner class
into an anonymous class.
12.5
Key concepts
• Interface.
A Java interface definition can have (in its body): (1) initializing
declarations of public static final variables and (2) declarations of public abstract
methods.
• Implementing an interface.
If a class
implements
an interface, the class inher-
its all the components that the interface declares (or inherits from superinter-
faces). Since the inherited methods are abstract, the class must provide overrid-
ing declarations for all the inherited methods.
• An interface as a type.
An interface is treated like a class-type. If a variable
vc
contains the name of some class
C
that implements an interface
I
, then
vc
can be
cast to
I
, e.g. as in the assignment
I vi= (I) vc;
. This is a widening cast, and
such widening casts do not have to be explicitly requested. The apparent type of
variable
vi
is
I
, so that, syntactically speaking, only the components defined in
I
can be referenced using
vi
. However, such a widening cast does not lose infor-
mation, and
vi
can be cast with a narrowing cast back to
C
, e.g. with
(C) vc
.
Then, all the components declared in or inherited by
C
can be referenced.
• Multiple inheritance.
A class can implement more than one interface. In doing
public static class
Out {
/** =
an
Iterator
over
b
's
elements in reverse */
public static
Iterator revIt(
final
Object[] b) {
/**
a (reverse)
Iterator
over
b */
class
ItOver
implements
Iterator <
body of class
>
return new
ItOver();
}
}
Figure 12.23:
Interface Iterator
public static
class Out {
/** =
an
Iterator
over
b
's elements in reverse
*/
public static
Iterator revIt(
final
Object[] b) {
return new
Iterator() <
body of class
>
}
}
Figure 12.24:
An anonymous class
Search WWH ::
Custom Search