Java Reference
In-Depth Information
Line 10: Box via boxRef
Length = 13.0, Width = 7.0, Height = 4.0, Surface Area = 342.0, Volume = 364.0
Line 12: rectRef is an instance of BoxShape
Line 18: rectangle is not an instance of BoxShape
The preceding program works as follows: The statement in Line 1 declares
rectangle
and
rectRef
to be reference variables of the
RectangleShape
type. Similarly, the
statement
in Line 2 declares
box
and
boxRef
to be reference variables of
the
BoxShape
type.
The statement in Line 3 instantiates the object
rectangle
and initializes the instance
variables
length
and
width
to
12.0
and
4.0
, respectively. The statement in Line 4
outputs the length, width, perimeter, and area of
rectangle
.
The statement in Line 5 instantiates the object
box
and initializes the instance variables
length
,
width
, and
height
to
13.0
,
7.0
, and
4.0
, respectively. The statement in Line
6 outputs the length, width, height, surface area, and volume of
box
.
The statement in Line 7 copies the value of
box
into
rectRef
. After this statement
executes,
rectRef
points to the object
box
. Notice that
rectRef
is a reference variable
of the
RectangleShape
(the superclass) type and
box
is a reference variable of the
BoxShape
(the subclass of
RectangleShape
) type.
The statement in Line 8 outputs the length, width, height, surface area, and volume of
box
via the reference variable
rectRef
. Notice that
rectRef
is a reference variable of
the
RectangleShape
type. However, when the statement in Line 8 executes to output
rectRef
, the method
toString
of the
class
BoxShape
executes, not the method
toString
of the
class
RectangleShape
.
Because the reference variable
rectRef
points to an object of
BoxShape
, the statement
in Line 9 uses the cast operator and copies the value of
rectRef
into
boxRef
. (If the
reference variable
rectRef
did not point to an object of type
BoxShape
, then
the statement in Line 9 would result in an error.) The statement in Line 10 outputs the
length, width, height, surface area, and volume of the object to which
boxRef
points.
The statements in Lines 11 through 14 determine whether
rectRef
is an instance of
BoxShape
, that is, if
rectRef
points to an object of the
BoxShape
type. Similarly, the
statements in Lines 15 through 18 determine whether the reference variable
rectangle
is an instance of
BoxShape
.
An abstract method is a method that has only the heading with no body. The heading
of an abstract method contains the reserved word
abstract
and ends with a semicolon.
The following are examples of abstract methods:
Search WWH ::
Custom Search