Java Reference
In-Depth Information
figure 15.6
Iterator/container
relationship
v
items: 3,5,2
container
current=3
container
current=0
itr1
itr2
Since we know that itr1 must be tied to one and only one iterator, it
seems that the expression container.items is redundant: If the iterator could
only remember the container that constructed it, we wouldn't have to keep
track of it ourselves. And if it remembered it, we might expect that if inside
of the LocalIterator we referred to items , then since the LocalIterator does
not have an items field, the compiler (and run-time system) would be smart
enough to deduce that we are talking about the items field of the MyContainer
object that caused the construction of this particular LocalIterator . This is
exactly what an inner class does, and what distinguishes it from a nested
class.
The big difference between an inner class and a nested class is that when
an instance of an inner class object is constructed, there is an implicit refer-
ence to the outer class object that caused its construction. This implies that an
inner class object cannot exist without an outer class object for it to be
attached to, with an exception being if it is declared in a static method
(because local and anonymous classes are technically inner classes), a detail
we will discuss later.
If the name of the outer class is Outer , then the implicit reference is
Outer.this . Thus, if LocalIterator was declared as an instance inner class (i.e.,
the static keyword was removed), then the MyContainer.this reference could
be used to replace the container reference that the iterator is storing. The pic-
ture in Figure 15.7 illustrates that the structure would be identical. A revised
class is shown in Figure 15.8.
In the revised implementation, observe that LocalIterator no longer has
an explicit reference to a MyContainer , and also observe that its constructor is
no longer necessary, since it only initialized the MyContainer reference.
Finally, Figure 15.9 illustrates that just as using this is optional in an instance
method, the Outer.this reference is also optional if there is no name clash.
Thus, MyContainer.this.size can be shortened to size , as long as there is no
other variable named size that is in a closer scope.
The big difference
between an inner
class and a nested
class is that when
an instance of an
inner class object
is constructed,
there is an implicit
reference to the
outer class object
that caused its
construction.
If the name of the
outer class is Outer ,
then the implicit
reference is
Outer.this .
 
 
Search WWH ::




Custom Search