Experiment 2: Constructors for Subclasses


One way of viewing how objects are constructed is via an onion model. Each subclass has contained within it an instance of its parent class. For example, if we create an instance of RegularAccount, we also get a MinimumAccount and so forth up the chain of inheritance.

 

Part of what we need to do when we construct a RegularAccount, is to invoke the constructor of its superclass. Not only that, but we need to finish constructing our inner layers before doing an outer layer.

Look at the code for the constructor of RegularAccount.

   public RegularAccount ( String name, String pin, double initial) 
   {
      super(name, pin, MINIMUM, PENALTY);
      deposit(initial);
   }	

Form a hypothesis about the method of each of the two lines in the constructor.





Super

Predict what will happen if the super() line is commented out.






Do so, and report the results in the space below:








If your prediction was shown to be incorrect, explain why.







Deposit

Predict what will happen if just the deposit() line is commented out.






Do so, and report the results in the space below:








If your prediction was shown to be incorrect, explain why.








Order of construction

Predict what will happen if the order of the deposit() and super() lines were switched






Do so, and report the results in the space below:








If your prediction was shown to be incorrect, explain why.








You should now have a better understanding of how constructors work in the context of a class hierarchy.

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.