Java Reference
In-Depth Information
not need to know about it. Further, it would be nice to structure the program so
that
Transaction
s for an account are connected more closely to that account
instead of using a field
account
to indicate which account it is.
To do this, we make class
Transaction
an inner class of
BankAccount
, as
shown in Fig. 12.14. You already know that non-static fields
account
and
bal-
ance
belong in each instance of
BankAccount
. Since class
Transaction
is also
nonstatic, a file drawer for it also belongs in each instance of
BankAccount
.
Since each instance of
Transaction
is within a
Transaction
file drawer,
Get the class
of Fig. 12.15
from lesson
page 12.6.
/**
A bank account
*/
public class
BankAccount {
/**
a
ccount number, amount in account, and last transaction carried out
("deposit" or "withdrawal" */
private int
account;
private int
balance;
private
Transaction lastTransaction;
//
Getter and setter methods omitted.
/**
Deposit amount in this account
*/
public void
deposit(
int
amount) {
balance= balance + amount;
lastTransaction=
new
Transaction(amount, "deposit");
}
/**
Withdraw
amount
from this account
*/
public void
withdraw(
int
amount) {
balance= balance - amount;
lastTransaction=
new
Transaction(amount, "withdrawal");
}
/**
A bank-account transaction
*/
private
class Transaction {
/**
type of transaction (
"deposit"
,
"withdrawal") and amount */
String transaction;
int
amount;
/**
Constructor: instance for this account, kind
t
, amount
n */
public
Transaction(
int
n, String t)
{ transaction= t; amount= n; }
/**
representation of this
Transaction */
public
String toString()
{
return
account + ": " + transaction + " " + amount; }
}
}
Program 12.14:
Class
BankAccount
, with inner class
Transaction
Search WWH ::
Custom Search