Using super
In the preceding examples, classes derived from Box were not implemented as efficiently or
as robustly as they could have been. For example, the constructor for BoxWeight explicitly
initializes the width, height, and depth fields of Box( ). Not only does this duplicate code
found in its superclass, which is inefficient, but it implies that a subclass must be granted access
to these members. However, there will be times when you will want to create a superclass that
keeps the details of its implementation to itself (that is, that keeps its data members private).
In this case, there would be no way for a subclass to directly access or initialize these variables
on its own. Since encapsulation is a primary attribute of OOP, it is not surprising that Java
provides a solution to this problem. Whenever a subclass needs to refer to its immediate
superclass, it can do so by use of the keyword super.
super has two general forms. The first calls the superclass' constructor. The second is
used to access a member of the superclass that has been hidden by a member of a subclass.
Each use is examined here.
Using super to Call Superclass Constructors
A subclass can call a constructor defined by its superclass by use of the following form of super:
Here, arg-list specifies any arguments needed by the constructor in the superclass. super( )
must always be the first statement executed inside a subclass' constructor.
To see how super( ) is used, consider this improved version of the BoxWeight( ) class:
// BoxWeight now uses super to initialize its Box attributes.
class BoxWeight extends Box {
double weight; // weight of box
// initialize width, height, and depth using super()
BoxWeight(double w, double h, double d, double m) {
super(w, h, d); // call superclass constructor
weight = m;
Here, BoxWeight( ) calls super( ) with the arguments w, h, and d. This causes the Box( )
constructor to be called, which initializes width, height, and depth using these values.
BoxWeight no longer initializes these values itself. It only needs to initialize the value unique
to it: weight. This leaves Box free to make these values private if desired.
In the preceding example, super( ) was called with three arguments. Since constructors
can be overloaded, super( ) can be called using any form defined by the superclass. The
constructor executed will be the one that matches the arguments. For example, here is a
complete implementation of BoxWeight that provides constructors for the various ways
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks