Experiment 4: Overriding Inherited Methods

As we move down the hierarchy, we get to more specialized classes. What may have been appropriate general behavior for the super class may no longer be appropriate for the subclass. For example, consider our BasicAccount class. By default it is a subclass of Object. It therefore, inherits the public method toString() of the Object class.

Lets find out what that method does. Comment out the toString() method in the BasicAccount class and then compile and run the code. Record your results here and contrast them with previous results.

The toString() method in BasicAccount completely overrides the toString() method in Object. When that message is sent to a RegularAccount, the first class in the hierarchy that responds to it is BasicAccount. It is handled at that level and the toString() method in Object is never invoked.

Change the code for BasicAccount back to the original.


Suppose that we added the following code into the RegularAccount class.

	public void deposit( double amount, String pin) {
		double myBalance = 0.0;
		myBalance += amount;

Predict the result of running the demo.

Run the demo and show your results

If your result was different, explain why.

This kind of code could have arisen from a poor understanding of how inheritance works. The implementer decides that the security code is "just too slow" and decides to override the deposit method to make it faster. They probably started with code like

	public void deposit( double amount, String pin) {
		myBalance += amount;

But when that failed to compile, added in the extra line.

Thought experiment

There is a way that the PIN checking of the security layer can be avoided. Making changes only in the deposit() method in RegularAccount describe how can it be done. Note that while this is "legal", it is not recommended.

Implement your proposal and demonstrate that it works by adding in the following lines to AccountDemo.java. Once you are successful comment out the changes.

   theScreen.println("Bad Pin Depositing 111.00 ");
   anAccount.deposit(111.00, "122");
   theScreen.println("\nAccount status is: " + anAccount);


Back to the Exercise List

Forward to the Next Experiment

Back to the Table of Contents

Back to the Introduction

Copyright 2000 by Prentice Hall. All rights reserved.