Java Reference
In-Depth Information
In the preceding section, we defined the class Rectangle and derived the class Box
from it. Moreover, we illustrated how to override a method of the class Rectangle .
We now discuss how to write the definitions of the constructors of the class Box .
The class Rectangle has two constructors and two instance variables. The class Box
has three instance variables: length , width , and height . The instance variables length
and width are inherited from the class Rectangle .
To write the definitions of the constructors of the class Box , we first write the definition
of the default constructor of the class Box . Recall that if a class contains the default
constructor and no values are specified during object instantiation, the default constructor
executes and initializes the object. Because the class Rectangle contains the default
constructor, when we write the definition of the default constructor of the class Box ,to
(explicitly) specify a call to the default constructor of the class Rectangle , we use the
reserved word super with no parameters, as shown in the following code. Also, a call to
the (default) constructor of the superclass must be the first statement.
public Box()
{
super ();
height = 0;
}
Next, we discuss how to write the definitions of the constructors with parameters.
(Note that if you do not include the statement super (); , then, by default, the default
constructor of the superclass (if any), will be called.)
To specify a call to a constructor with parameters of the superclass, we use the reserved
word super with the appropriate parameters. A call to the constructor of the superclass
must be the first statement.
Consider the following definition of the constructor with parameters of the class Box :
1
0
public Box( double l, double w, double h)
{
super (l, w);
height = h;
}
This definition specifies the constructor of Rectangle with two parameters. When this
constructor of Box executes, it triggers the execution of the constructor with two
parameters of type double of the class Rectangle .
(Note that invoking a superclass constructor's name in a subclass will result in a syntax error.
Also, because a call to a constructor of the superclass must be the first statement, within the
definition of a constructor of a subclass only one constructor of the superclass can be invoked.)
As an exercise, try writing the complete definition of the class Box .
Consider the following statements:
Rectangle myRectangle = new Rectangle(5, 3);
//Line 1
Box myBox = new Box(6, 5, 4);
//Line 2
Search WWH ::




Custom Search