/** A bank account has a balance that can be changed by deposits and withdrawals. */ public class BankAccount { private double balance; /** Constructs a bank account with a zero balance. */ public BankAccount() { balance = 0; } /** Constructs a bank account with a given balance. @param initialBalance the initial balance */ public BankAccount(double initialBalance) { balance = initialBalance; } /** Deposits money into the bank account. @param amount the amount to deposit */ public void deposit(double amount) { balance = balance + amount; } /** Withdraws money from the bank account. @param amount the amount to withdraw */ public void withdraw(double amount) { balance = balance - amount; } /** Gets the current balance of the bank account. @return the current balance */ public double getBalance() { return balance; } }
/** A class to test the BankAccount class. */ public class BankAccountTester { /** Tests the methods of the BankAccount class. @param args not used */ public static void main(String[] args) { BankAccount harrysChecking = new BankAccount(); harrysChecking.deposit(2000); harrysChecking.withdraw(500); System.out.println(harrysChecking.getBalance()); System.out.println("Expected: 1500"); } }
Classwork:
- Add a method sayGoodbye to the Greeter class.
-
Add a method refuseHelp to the Greeter class. It should return a string such as “I am sorry, Dave. I am afraid I can’t do that.”
-
Write a program that constructs a bank account, deposits $1000, withdraws $500, withdraws another $400, and then prints the remaining balance.
-
Add a method
void addInterest(double rate)
to the BankAccount class that adds interest at the given rate. For example, after the statemetns
BankAccount momsSavings = new BankAccount(1000); momsSavings.addInterest(10); // 10% interest
the balance in momsSavings is $1,100.