Java Reference
In-Depth Information
You can also use the
import static
directive to import a
static member type. See
“Packages and the Java Namespace”
on page 88
in
Chapter 2
for details on
import
and
import
static
.
However, importing a nested type obscures the fact that that type is closely associ‐
ated with its containing type—which is usually important information—and as a
result it is not commonly done.
Nonstatic Member Classes
A
nonstatic member class
is a class that is declared as a member of a containing class
or enumerated type without the
static
keyword:
• If a static member type is analogous to a class field or class method, a nonstatic
member class is analogous to an instance field or instance method.
• Only classes can be nonstatic member types.
• An instance of a nonstatic member class is always associated with an instance
of the enclosing type.
• The code of a nonstatic member class has access to all the fields and methods
(both
static
and non-
static
) of its enclosing type.
• Several features of Java syntax exist specifically to work with the enclosing
instance of a nonstatic member class.
m
e
Example 4-2
shows how a member class can be defined and used. This example
extends the previous
LinkedStack
example to allow enumeration of the elements on
the stack by defining an
iterator()
method that returns an implementation of the
java.util.Iterator
interface. The implementation of this interface is defined as a
member class.
Example 4-2. An iterator implemented as a member class
import
java.util.Iterator
;
public
class
LinkedStack
{
// Our static member interface
public
interface
Linkable
{
public
Linkable
getNext
();
public
void
setNext
(
Linkable
node
);
}
// The head of the list
private
Linkable
head
;
// Method bodies omitted here