/* Account.java -- define a bank account. When you open an account, there * is an initial balance and interest rate. Then, you can perform * transactions -- deposit, withdraw, earn interest and write checks. * We'll assume that if the user opens an account with no money, they'll * earn 2%, otherwise 3%. * This is not a realistic example -- real banks don't operate this way, * but this program is mainly about reviewing good program structure. */ public class Account { // attributes of a bank account private double balance; private double interestRate; private int checkNumber; // Constructors public Account() { balance = 0.00; interestRate = 2.0; checkNumber = 101; } public Account(double initial) { balance = initial; interestRate = 3.0; checkNumber = 501; } public Account(Account a) { balance = a.balance; interestRate = a.interestRate; checkNumber = 1001; } // Other methods that implement routine operations. // Notice that all these functions use attribute variables balance // and/or interestRate. For clarity, we could have typed "this.balance" // and "this.interestRate" because attributes belong to "this". public double getBalance() { return balance; } public void deposit(double amount) { balance += amount; } public void withdraw(double amount) { balance -= amount; } public void accrueInterest() { balance *= (1 + interestRate/100.0); } /* When we write a check, tell the user what the check number is, * deduct the amount from the balance, and increment the check number. * Actually, we should also check for overdraft... */ public void writeCheck(double amount) { System.out.printf("Check # %d has cleared.\n", checkNumber); balance -= amount; ++checkNumber; } /* Let's transfer money to another account. This method will take * an Account parameter "a", and this is the account we are sending * money to. The second parameter tells how much money to transfer. */ public void transfer(Account a, double amount) { this.withdraw(amount); a.deposit(amount); } // The toString function allows us to print somebody's balance. public String toString() { return String.format("$ %.2f", balance); } }