Java Reference
In-Depth Information
1 // The iterator class as an inner class
2 private class LocalIterator implements Iterator
3 {
4 private int current = 0;
5
6 public boolean hasNext( )
7 { return current < size; }
8
9 public Object next( )
10 { return items[ current++ ]; }
11 }
figure 15.9
Inner class;
Outer.this may be
optional.
For instance, suppose we suspend belief for a minute and imagine that
LocalIterator is public. We do so only to illustrate the complications that the
language designers face when adding a new language feature. Under this
assumption the iterator's type is MyContainer.LocalIterator , and since it is visi-
ble, one might expect that
MyContainer.LocalIterator itr = new MyContainer.LocalIterator( );
is legal, since like all classes, it has a public default zero-parameter construc-
tor. However, this cannot possibly work, since there is no way to initialize the
implicit reference. Which MyContainer is itr referring to? We need some syn-
tax that won't conflict with any other language rules. Here's the rule: If there
is a container c , then itr could be constructed using a bizarre syntax invented
for just this case, in which the outer object in effect invokes new :
MyContainer.LocalIterator itr = c.new LocalIterator( );
Notice that this implies that in an instance factory method, this.new is
legal, and shorthands to the more conventional new seen in a factory method. If
you find yourself using the bizarre syntax, you probably have a bad design. In
our example, once LocalIterator is private, this entire issue goes away, and if
LocalIterator is not private, there is little reason to use an inner class in the
first place.
There are also other rules, some of which are arbitrary. Private members
of the inner or nested class are public to the outer class. To access any mem-
ber of an inner class, the outer class only needs to provide a reference to an
inner class instance and use the dot operator, as is normal for other classes.
Thus inner and nested classes are considered part of the outer class.
Both inner and nested classes can be final, or they can be abstract, or they
can be interfaces (but interfaces are always static, because they cannot have
any data, including an implicit reference), or they can be none of these. Inner
Search WWH ::




Custom Search