Java Reference
In-Depth Information
Box
-height:
double
+Box()
+Box(
double
,
double
,
double
)
+setDimension(
double
,
double
,
double
):
void
+getHeight():
double
+area():
double
+volume():
double
+toString():
String
Rectangle
Box
FIGURE 10-3
UML class diagram of the
class
Box
and the inheritance hierarchy
From the definition of the
class
Box
, it is clear that the
class
Box
is derived from the
class
Rectangle
. Therefore, all
public
members of
Rectangle
are
public
members
of
Box
. The
class
Box
overrides the methods
toString
and
area
, and overloads the
method
setDimension
.
In general, when writing the definitions of the methods of a subclass to specify a call to a
public
method of a superclass, you do the following:
If the subclass overrides a
public
method of the superclass, then you
must specify a call to that
public
method of the superclass by using the
reserved word
super
, followed by the dot operator, followed by the
method name with an appropriate parameter list. In this case, the general
syntax to call a method of the superclass is:
super
.methodName(parameters);
If the subclass does not override a
public
method of the superclass, you
can specify a call to that
public
method by using the name of the
method and an appropriate parameter list.
Next, let's write the definition of the method
toString
of the
class
Box
.
The
class
Box
has three instance variables:
length
,
width
, and
height
. The method
toString
of the
class
Box
prints the values of these three instance variables. To write
the definition of the method
toString
of the
class
Box
, remember the following:
The instance variables
length
and
width
are
private
members of the
class
Rectangle
and so cannot be directly accessed in the
class
Box
.
Therefore, when writing the definition of the method
toString
of the
class
Box
, you cannot directly reference
length
and
width
.
Search WWH ::
Custom Search