Java Reference
In-Depth Information
Of course, during this time, other things in other threads may be going on. There are no instance
variables to initialize in a Bank object so we don't need a constructor. Since our Bank object works
using a Transaction object, let's define the class for that next.
Try It Out - Defining a Transaction on an Account
The Transaction class could represent any transaction on an account, but we are limiting ourselves
to debits and credits. We can define the class as:
class Transaction {
// Transaction types
public static final int DEBIT = 0;
public static final int CREDIT = 1;
public static String[] types = {"Debit","Credit"};
// Constructor
public Transaction(Account account, int transactionType, int amount) {
this.account = account;
this.transactionType = transactionType;
this.amount = amount;
}
public Account getAccount() {
return account;
}
public int getTransactionType() {
return transactionType;
}
public int getAmount() {
return amount;
}
public String toString() {
return types[transactionType] + " A//C: " + ": $" + amount;
}
private Account account;
private int amount;
private int transactionType;
}
How It Works
The type of transaction is specified by the transactionType field that must be one of the values
defined for transaction types. We should build in checks in the constructor to ensure only valid
transactions are created, but we'll forego this to keep the code volume down, and you certainly know
how to do this sort of thing by now. A transaction records the amount for the transaction and a
reference to the account to which it applies, so a Transaction object specifies a complete transaction.
The methods are very straightforward, just accessor methods for the data members that are used by the
Bank object, plus the toString() method in case we need it.
Search WWH ::




Custom Search