Java Reference
In-Depth Information
The statement in Line 7 creates the
Box
object
myBox1
and initializes its instance variables
to
0
. The statement in Line 8 creates the
Box
object
myBox2
and initializes its instance
variables
length
,
width
, and
height
to
10.0
,
7.0
, and
3.0
, respectively.
The statements in Lines 9 and 10 output the length, width, and area of
myRectangle1
.
Because the instance variables of
myRectangle1
are initialized to
0
by the default con-
structor, the area of the rectangle is
0.0
square units, as shown in the output of Line 10.
The statements in Lines 11 and 12 output the length, width, and area of
myRectangle2
.
Because the instance variables
length
and
width
of
myRectangle2
are initialized to
8.0
and
6.0
, respectively, by the constructor with parameters, this rectangle's area is
48.0
square units. See the output of Line 12.
The statements in Lines 13, 14, and 15 output the length, width, height, surface area, and
volume of
myBox1
. Because the instance variables of
myBox1
are initialized to
0.0
by the
default constructor, this box's surface area is
0.0
square units and the volume is
0.0
cubic
units. See the output of Lines 14 and 15.
The statements in Lines 16, 17, and 18 output the length, width, height, surface area, and
volume of
myBox2
. Because the instance variables
length
,
width
, and
height
of
myBox2
are initialized to
10.0
,
7.0
, and
3.0
, respectively, by the constructor with
parameters, this box's surface area is
242.0
square units and the volume is
210.0
cubic
units. See the output of Lines 17 and 18.
The output of this program demonstrates that the redefinition of the methods
toString
and
area
in the
class
Box
applies only to the objects of type
Box
.
(
Shadowing Variables) Suppose that the
class
SubClass
is derived from the
class
SuperClass
and
SuperClass
has a variable named
temp
. You can declare a variable
named
temp
in the
class
SubClass
. In this case, the variable
temp
of
SubClass
is
called a shadowing variable. The concept of a shadowing variable is similar to the concept of
overriding a method, but it causes confusion. Now the
SubClass
is derived from
SuperClass
, so it inherits the variable
temp
of
SuperClass
.Becauseavariablenamed
temp
is already available in
SubClass
, there is seldom if ever any reason to override it.
Furthermore, it is poor programming practice to override a variable in the
SubClass
.
Anyone reading code with a shadowed variable will have two different declarations of a
variable seeming to apply to the shadowed variable of the
SubClass
. This causes confusion
and should be avoided. In general, you should avoid shadowing variables.
Next, we give another example illustrating how to create a subclass.
EXAMPLE 10-3
Suppose that you want to define a class to group the attributes of an employee. There are full-
time employees and part-time employees. Part-time employees are paid based on the
Search WWH ::
Custom Search