Java Reference
In-Depth Information
and since the file drawer is within some instance of BankAccount , the general
inside-out rule indicates that methods in class Transaction can access fields
balance and account . This means that field account of class Transaction is
no longer needed, so we removed it from the inner class. We have achieved a
closer bond between classes Transaction and BankAccount .
We also made class Transaction private so that it cannot be referenced out-
side class BankAccount , thus following the principle of information hiding.
Finally, simply to illustrate the creation of instances of class Transaction ,
we added a field to BankAccount to contain the last transaction that was carried
out; and we added statements to methods deposit and withdraw to create a
Transaction and store it in the new field trans .
This example illustrates three reasons for using an inner class:
1. To improve the structure of the program.
2. To hide a class.
3. To make it possible for the inner class to reference non-static components
of instances of the outer class.
When to use an inner class
Here is a general guideline for when to make a class an inner class.
/** A list of bank accounts */
public class Bank {
// Class invariant: the accounts are in bank[0..size-1]
private BankAccount[] bank;
private int size;
/** A (reverse) iterator for bank accounts */
public class BAIterator implements Iterator {
/** bank[0..n-1] remains to be enumerated */
private int n= size; // ILLEGAL REFERENCE TO size
/** = " there is another account to be enumerated. " */
public boolean hasNext()
{ return n > 0; }
/** = the next item to be enumerated */
public Object next() {
n= n - 1;
return bank[n]; // ILLEGAL REFERENCE TO bank
Figure 12.15:
Class Bank and BAIterator (as separate files)
Search WWH ::

Custom Search