Java Reference
In-Depth Information
Class BAIterator has several problems. For example, it cannot access the
array of accounts or field size of class Bank directly (as attempted in the initial-
ization of field n ). So, Bank has to have getter methods for fields bank and size ,
and an instance of class Bank has to be passed to the Iterator . But then BAIt-
erator needs a constructor that has an object of class Bank as parameter. Thus,
several complications arise in attempting to get the two classes to communicate.
These problems arise because BAIterator is separate from class Bank . The
solution to these problems is to make BAIterator an inner class of Bank , as
shown in Fig. 12.16.
Now, by the inside-out rule, the references to size and bank within class
BAIterator refer directly to fields bank and size of class Bank .
Note that we made class BAIterator private so that it cannot be referenced
from outside. But we provide method iterator to obtain new instances of
BAIterator . The return type of method iterator is not BAIterator but Iter-
ator —the user of class Bank does not even know about the name BAIterator
and can never reference it. This is the standard way of making such an iterator
available outside the class.
Study this class and its inner class carefully; use this pattern whenever an
inner iterator class is desired.
Get the class
of Fig. 12.17
from lesson
page 12.6.
The file drawer for an inner class
In Fig. 12.17, we show a class Out with an inner class In . In our model of
execution, each class has a file drawer in a filing cabinet, and the question you
may ask is where the file drawer for inner class In goes. Each instance of Out is
supposed to contain the non-static components of Out . Since In is now a non-
static component, a file drawer for In is in each instance of Out !
Figure 12.18 contains an example of Out 's file drawer, with two manilla
folders and the static variable. Each folder of class Out contains a file drawer for
In , with one folder showing.
With respect to Fig. 12.17, the inside-out rule, which defines what a partic-
ular part of a program can reference directly, indicates the following with respect
Activity
12-6.2
public class Out {
public static int x;
private int y;
public int meth() {...}
class In {
int z;
void meth2()
{ z= y; }
}
}
Figure 12.17:
Classes to illustrate file drawers for inner classes
Search WWH ::




Custom Search