Java Reference
In-Depth Information
figure 15.7
Iterator/container with
inner classes
items:
3,5,2
v
MyContainer.this
MyContainer.this
current=3
current=0
itr1
itr2
figure 15.8
Iterator design using
inner class
1
package weiss.ds;
2
3
public class MyContainer
4
{
5
private Object [ ] items;
6
private int size = 0;
7
8
// Other methods for MyContainer not shown
9
10
public Iterator iterator( )
11
{ return new LocalIterator( ); }
12
13
// The iterator class as an inner class
14
private class LocalIterator implements Iterator
15
{
16
private int current = 0;
17
18
public boolean hasNext( )
19
{ return current < MyContainer.this.size; }
20
21
public Object next( )
22
{ return MyContainer.this.items[ current++ ]; }
23
}
24
}
Local classes and anonymous classes do not specify whether they are
static
, and they are always technically considered inner classes. However, if
such a class is declared in a static method, it has no implicit outer reference
(and thus behaves like a nested class), whereas if it is declared inside an
instance method, its implicit outer reference is the invoker of the method.
The addition of inner classes requires a significant set of rules, many of
which attempt to deal with language corner cases and dubious coding practices.
Search WWH ::
Custom Search