Java Reference
In-Depth Information
public
void
push
(
Linkable
node
)
{
...
}
public
Linkable
pop
()
{
...
}
// This method returns an Iterator object for this LinkedStack
public
Iterator
<
Linkable
>
iterator
()
{
return
new
LinkedIterator
();
}
// Here is the implementation of the Iterator interface,
// defined as a nonstatic member class.
protected
class
LinkedIterator
implements
Iterator
<
Linkable
>
{
Linkable
current
;
// The constructor uses a private field of the containing class
public
LinkedIterator
()
{
current
=
head
;
}
// The following 3 methods are defined by the Iterator interface
public
boolean
hasNext
()
{
return
current
!=
null
;
}
public
Linkable
next
()
{
if
(
current
==
null
)
throw
new
java
.
util
.
NoSuchElementException
();
Linkable
value
=
current
;
current
=
current
.
getNext
();
return
value
;
}
public
void
remove
()
{
throw
new
UnsupportedOperationException
();
}
}
}
Notice how the
LinkedIterator
class is nested within the
LinkedStack
class.
Because
LinkedIterator
is a helper class used only within
LinkedStack
, having it
defined so close to where it is used by the containing class makes for a clean design,
just as we discussed when we introduced nested types.
Features of member classes
Like instance fields and instance methods, every instance of a nonstatic member
class is associated with an instance of the class in which it is defined. This means
that the code of a member class has access to all the instance fields and instance
methods (as well as the
static
members) of the containing instance, including any
that are declared
private
.
This crucial feature was already illustrated in
Example 4-2
. Here is the
Linked
Stack.LinkedIterator()
constructor again:
public
LinkedIterator
()
{
current
=
head
;
}
This single line of code sets the
current
field of the inner class to the value of the
head
field of the containing class. The code works as shown, even though
head
is
declared as a
private
field in the containing class.