For preparation, Review Topic 4 of the lecture notes (the
super, overriding methods, superclass variables,
polymorphism, dynamic binding). You might find it helpful to bring the
Topic 4 notes to the Lab, to help you in answering the questions of
Exercise 2. Make sure you understand the code for
BankAccount class and
Download the BankAccount class and the CheckingAccount classes, and create a new project for these files.
Create a new
SavingsAccount class in your project,
which extends the
BankAccount class. It will contain an
additional attribute besides the one inherited from
BankAccount class: the interest rate (a double) for a
savings account. It will
also contain the following methods:
public SavingsAccount(double initialAmount, double rate)
public void calculateInterest(), which calculates one month's interest and adds the amount to the balance
public String toString(), which returns a string representation of the account's attributes (balance and interest rate)
Download the file
TestBankAccounts.java and add it to your project. It has a main method that
so far only creates some bank account objects of the three types
In each step of this exercise, you will be adding statements to the main method, running it after each addition. Answer the questions at each step. If there is a compilation error, make sure you remove (or comment out) the offending statement before advancing to the next step of this exercise.
TestBankAccounts(code must be added near the end of the
mainmethod, after the last comment line):
bacc0 = chacc1; which makes the BankAccount variable
bacc0reference the CheckingAccount object referenced by
chacc1. Was this legal? Why?
System.out.println(bacc0.toString());and run. Which
toStringmethod did it use, the one from the
BankAccountclass or the one from the
BankAccountobject referenced by
bacc1, and compile. Was this legal? Why not?
BankAccount bacc2 = new CheckingAccount(200.0);. Now suppose we want the variable
chacc1to reference this new object: add the statement
chacc1 = bacc2;. Fix this statement so that it compiles and runs, using casting.
deductFeeson objects of all three types (i.e. on variables
sacc1). On which type of objects was this legal? Why?
chacc1.deposit(100.0);Your program should compile and run. Now make the following change to
CheckingAccount.java: in the code for the deposit method, change
deposit(amount);Compile and run. What was the runtime error, and why do you think it happened?