import java.text.DecimalFormat; /**** * * Class BankAccount is a simple banking example based on the example of the * same name from Horstmann Chapter 10, with a couple enhancements. It has a * balance that can be changed by deposit and withdrawal methods. It also * provides a method to get the current balance. * * The enhancements are string data field for the name of the banking * institution and a toString method. These enhancments are useful in the * companion BankAccountManger class. * */ public class BankAccount { /** The current balance of this bank account. */ private double balance; /** Name of the banking institution for this account. */ private String institution; /** * Construct a bank account with a zero balance. */ public BankAccount() { balance = 0; } /** * Construct a bank account at the given institution, with the given * initial balance. */ public BankAccount(String institution, double balance) { this.balance = balance; this.institution = institution; } /** * Deposit the given amount of money into this bank account. */ public void deposit(double amount) { if (amount < 0) { throw new IllegalArgumentException(); } balance = balance + amount; } /** * Withdraw the given amount of money from this bank account. */ public void withdraw(double amount) { if ((balance - amount < 0) || (amount < 0)) { throw new IllegalArgumentException(); } balance = balance - amount; } /** * Get the current balance of this bank account. */ public double getBalance() { return balance; } /** * Transfer the given amount from this account to the given other account. */ public void transfer(double amount, BankAccount other) { withdraw(amount); other.deposit(amount); } /** * Return the string representation of this account in the form * * institution: $balance * * where the balance value is rounded to two decimal places. */ public String toString() { return institution + ": $" + new DecimalFormat(".##").format(balance); } }