/** * A bank account representation class. * DISCLAIMER: This code is for class illustration purposes and therefore * it is not written according to the course's style guidelines. */ public class BankAccount { // Account numbers are allocated from 1 onward. private static int nextAccountNumber = 1; // Money in the bank private static int bankDeposits = 0; // Commission rate that the bank charges private static final double COMMISSION_RATE = 0.005; // Commission step above which the commission halves private static final int COMMISSION_STEP = 5000; // Fields private int number; // Generated private String owner; // Supplied when an account is opened private double balance; // Supplied when an account is opened // Sets up a new account public BankAccount (String owner, double balance) { this.number = nextAccountNumber++; this.owner = owner; this.balance = balance; } // Handles a deposit public void deposit (double amount) { double charge = commission(amount); balance = balance + amount - charge; bankDeposits += amount; } // Handles a withdrawl public void withdraw (double amount) { double charge = commission(amount); balance = balance - amount - charge; bankDeposits -= amount; } // Handles a transfer public void transferTo(double amount, BankAccount targetAccount) { targetAccount.deposit(amount); this.withdraw(amount); } // Returns the balance public double getBalance () { return balance; } // Returns the commission that the bank charges for the amount private static double commission (double amount) { return ((amount > COMMISSION_STEP) ? (amount * COMMISSION_RATE / 2) : (amount * COMMISSION_RATE)); } // Accessors and mutators: in practice we will typically have one // accessor and one mutator for each field, here we have only two: public int getNumber() { return number; } public void setNumber(int number) { this.number = number; } // Returns a textual object description public String toString () { return (number + "\t" + owner + "\t" + (int) balance); } // Compares this object to another given object public boolean equals(BankAccount other) { if (other == null) { return false; } // Two bank accounts are equal if their account number is the same return (this.number == other.getNumber()); } // Returns a copy of this object public BankAccount clone() { BankAccount copy = new BankAccount(this.owner, this.balance); copy.setNumber(this.number); nextAccountNumber--; // restore the account numbetr "wasted" by the cloning return copy; } }