Java Reference
In-Depth Information
5.2. Inner Classes
Non-static nested classes are called inner classes. Non-static class mem-
bers are associated with instances of a classnon-static fields are instance
variables and non-static methods operate on an instance. Similarly, an
inner class is also (usually) associated with an instance of a class, or
more specifically an instance of an inner class is associated with an in-
stance of its enclosing classthe enclosing instance or enclosing object.
You often need to closely tie a nested class object to a particular object of
the enclosing class. Consider, for example, a method for the BankAccount
class that lets you see the last action performed on the account, such as
a deposit or withdrawal:
public class BankAccount {
private long number; // account number
private long balance; // current balance (in cents)
private Action lastAct; // last action performed
public class Action {
private String act;
private long amount;
Action(String act, long amount) {
this.act = act;
this.amount = amount;
}
public String toString() {
// identify our enclosing account
return number + ": " + act + " " + amount;
}
}
public void deposit(long amount) {
balance += amount;
lastAct = new Action("deposit", amount);
}
public void withdraw(long amount) {
 
Search WWH ::




Custom Search