Java Reference
In-Depth Information
balance -= amount;
lastAct = new Action("withdraw", amount);
}
// ...
}
The class
Action
records a single action on the account. It is not declared
static
, and that means its objects exist relative to an object of the en-
closing class.
The relationship between an
Action
object and its
BankAccount
object is
established when the
Action
object is created, as shown in the
deposit
and
withdraw
methods. When an inner class object is created, it must be
associated with an object of its enclosing class. Usually, inner class ob-
jects are created inside instance methods of the enclosing class, as in
deposit
and
withdraw
. When that occurs the current object
this
is associ-
ated with the inner object by default. The creation code in
deposit
is the
same as the more explicit
lastAct = this.new Action("deposit", amount);
Any
BankAccount
object could be substituted for
this
. For example, sup-
pose we add a transfer operation that takes a specified amount from
one account and places it in the current accountsuch an action needs to
update the
lastAct
field of both account objects:
public void transfer(BankAccount other, long amount) {
other.withdraw(amount);
deposit(amount);
lastAct = this.new Action("transfer", amount);
other.lastAct = other.new Action("transfer", amount);
}