import java.util.Vector; public class Checkbook { /** This vector stores any number of transactions (until memory is full) */ private Vector transactions = null; /** The current balance, which is always adjusted to the correct amount */ private double balance = 0.0; /** * Constructor to create an empty checkbook. */ public Checkbook() { super(); transactions = new Vector(); balance = 0.0; } /** * Adds a transaction to the list of current transactions, and adjusts the * balance accordingly. The method makes use of 'polymorphism', which will * pick the correct 'getAmount' method depending on the true type of 't' */ public void addTransaction(Transaction t) { transactions.add(t); balance += t.getAmount(); } /** * Returns the i-th transaction by retrieving the i-th element from the vector * and type-casting it to a transaction. Actually, the true type of the transaction * is retained automatically. */ public Transaction getTransaction(int i) { return (Transaction)transactions.get(i); } /** * Changes the status of the i-th transaction to 'status', where 'status' should be * Transaction.ACTIVE or Transaction.DELETED. Also updates the value of 'balance' * accordingly, making use of 'polymorphism' again. */ public void setStatusFor(int i, int status) { Transaction t = getTransaction(i); if ((t.getStatus() == Transaction.ACTIVE) && (status == Transaction.DELETED)) { balance -= t.getAmount(); t.setStatus(status); } if ((t.getStatus() == Transaction.DELETED) && (status == Transaction.ACTIVE)) { t.setStatus(status); balance += t.getAmount(); } } /** * Removes the i-th transaction from the list of current transactions and updates * the value of 'balance'. Uses the fact that getAmount returns 0 for a transaction * that has already been flagged as deleted. */ public void removeTransaction(int i) { Transaction t = getTransaction(i); balance -= t.getAmount(); transactions.remove(i); } /** * Returns the current balance, which is always accurate because the methods that could * potentially change its value update it automatically. */ public double getBalance() { return balance; } /** * Returns the current number of transaction. */ public int getSize() { return transactions.size(); } /** * Returns a string representation of the current checkbook. */ public String toString() { StringBuffer sb = new StringBuffer(); sb.append("Total number of transactions: " + getSize() + "\n"); sb.append("Total balance: " + getBalance() + "\n\n"); for (int i = 0; i < transactions.size(); i++) sb.append(transactions.get(i) + "\n\n"); return sb.toString(); } }