Java Reference
In-Depth Information
The instance variables
length
and
width
of the
class
Rectangle
are
accessible in the
class
Box
through the
public
methods of the
class
Rectangle
. Therefore, when writing the definition of the method
toString
of the
class
Box
, you first call the method
toString
of the
class
Rectangle
to print the values of
length
and
width
. After printing
the values of
length
and
width
, you output the value of
height
.
As stated above, to call the method
toString
of
Rectangle
in the definition of the
method
toString
of
Box
, you must use the following statement:
super
.toString ();
This statement ensures that you call the method
toString
of the superclass
Rectangle
,
not of the
class
Box
.
The definition of the method
toString
of the
class
Box
is:
public
String toString()
{
return super
.toString()
//retrieve length and width
+ "; Height = " + height;
}
Let's write the definitions of the remaining methods of the
class
Box
:
public void
setDimension(
double
l,
double
w,
double
h)
{
super
.setDimension(l, w);
if
(h >= 0)
height = h;
else
height = 0;
1
0
}
The
class
Box
overloads the method
setDimension
of the
class
Rectangle
.
Therefore, in the preceding definition of the method
setDimension
of the
class
Box
,
you can also specify a call to the method
setDimension
of the
class
Rectangle
without the reserved word
super
and the dot operator.
The definition of the method
getHeight
is:
public double
getHeight()
{
return
height;
}
The method
area
of the
class
Box
determines the surface area of the box. To do so, we
need to access the length and width of the box, which are declared as
private
members
of the
class
Rectangle
. Therefore, we use the methods
getLength
and
getWidth
of
the
class
Rectangle
to retrieve the length and width, respectively. Because the
class
Search WWH ::
Custom Search