Java Reference
In-Depth Information
1
package weiss.ds;
2
3
public class MyContainer
4
{
5
private Object [ ] items;
6
private int size = 0;
7
// Other methods for MyContainer not shown
8
9
public Iterator iterator( )
10
{ return new LocalIterator( this ); }
11
12
// The iterator class as a nested class
13
private static class LocalIterator implements Iterator
14
{
15
private int current = 0;
16
private MyContainer container;
17
18
private LocalIterator( MyContainer c )
19
{ container = c; }
20
21
public boolean hasNext( )
22
{ return current < container.size; }
23
24
public Object next( )
25
{ return container.items[ current++ ]; }
26
}
27
}
figure 15.5
Iterator design using
nested class
iterators and inner classes
15.2
An
inner class
is
similar to a nested
class in that it is
a class inside
another class and is
declared using the
same syntax as a
nested class,
except that it is not
a
static
class. An
inner class always
contains an implicit
reference to the
outer object that
created it.
In Section 15.1, we used a nested class to further hide details. In addition to
nested classes, Java provides inner classes. An
inner class
is similar to a
nested class in that it is a class inside another class and is treated as a member
of the outer class for visibility purposes. An inner class is declared using the
same syntax as a nested class, except that it is not a static class. In other
words, the
static
qualifier is missing in the inner class declaration.
Before getting into the inner class specifics, let us look at the problem that
they are designed to solve. Figure 15.6 illustrates the relationship between the
iterator and container classes that were written in the previous section. Each
instance of the
LocalIterator
maintains a reference to the container over
which it is iterating and a notion of the iterator's current position. The rela-
tionship that we have is that each
LocalIterator
must be associated with
exactly one instance of
MyContainer
. It is impossible for the
container
refer-
ence in any iterator to be
null
, and the iterator's existence makes no sense
without knowing which
MyContainer
object caused its creation.
Search WWH ::
Custom Search