Experiment 5: Using super


Frequently when we override a method, we don't want to completely replace the super class method. Instead we would like to do some extra work. Consider the MinimumAccount class as an example. We want to be able to detect if the balance has been lower than the minimum during the month. Each time the user makes a withdrawal, we want to do the regular deposit and we would like to also check the resulting balance and see if it is below the minimum. Therefore, we would like to override the withdraw() method. A first attempt might look something like:

	public void withdraw( double amount, String pin) {
		withdraw(amount, pin);
		if(balance() < myMinimum)
			chargePenalty = true;
	}	

Unfortunately this has a serious flaw. The withdraw() message inside our method will be sent to the object itself.

 

Predict what will happen if we change the code in MinimumAccount to match and add in the following lines to AccountDemo.java.

		theScreen.println("Withdrawing 90.00 ");
		anAccount.withdraw(90.0, "1202");
		theScreen.println("\nAccount status is: " + anAccount);





Make the changes and record your results here.





If your prediction doesn't match explain why.





We need to make sure that the method for our superclass is called. To direct our message appropriately, we need to have a super in front of the call.

	public void withdraw( double amount, String pin) {
		super.withdraw(amount, pin);
		if(balance() < myMinimum)
			chargePenalty = true;
	}	

Change the code in MinimumAccount and run the program again. Continue when the results produced are valid. Record the final balance here.





Fixing Minimum Account

As the code is now, there is a small bug in the implementation of MinimumAccount. If the account falls below the minimum balance due to a withdrawal, we will successfully charge a fee for that month. But suppose the user doesn't make any withdrawals after that. They may still be below the minimum, yet will not be charged. Fix the computeFees() method in MinimumAccount so that fees will be correctly computed in this case.

Change the AccountDemo.java code to demonstrate that your modifications are correct.


Back to the Exercise List


Back to the Table of Contents

Back to the Introduction


Copyright 2000 by Prentice Hall. All rights reserved.