Java Reference
In-Depth Information
Chapter
12
Interfaces and Nested Classes
OBJECTIVES
• Learn what an interface is.
• Study interfaces that provide comparisons:
Comparable
and
Comparator
.
• Study interfaces for enumerating data:
Enumerator
and
Iteration
.
• Learn about nested static classes, inner classes, and anonymous classes.
• Learn about the flattened view of nested classes, which is used by Java.
INTRODUCTION
We study two object-oriented features of Java. The
interface
provides a way of
ensuring syntactically (at compile time) that a class contains certain methods. The
nested class
allows one to define one class inside another. This means that an
object of the inner class can reside in an object of the outer class, allowing the
inner-class object to reference directly the components of the outer-class object.
The two features are independent, and either can be studied first.
12.1
Interfaces
In Chap. 4, we discussed the notion of an abstract class, like the following one:
Lesson page
12-1
public abstract class
C {
public abstract void
doIt(
int
par);
public abstract int
giveInt(
char
c);
}
Methods
doIt
and
giveInt
are abstract —first, because they include keyword
abstract
; second, because their bodies have been replaced by semicolons. Any
(non-abstract) class that extends
C
must implement these two methods.
We now introduce another mechanism, the Java
interface
, which provides
Search WWH ::
Custom Search