Java Reference
In-Depth Information
Consider the following application program:
// This program illustrates how polymorphic reference variables
// work.
public class
Polymorphism
//Line 1
{
//Line 2
public static void
main(String[] args)
//Line 3
{
//Line 4
RectangleFigure rectangle, shapeRef;
//Line 5
BoxFigure box;
//Line 6
rectangle
=
new
RectangleFigure(8, 5);
//Line 7
box =
new
BoxFigure(10, 7, 3);
//Line 8
shapeRef = rectangle;
//Line 9
System.out.println("Line 10: Rectangle:\n"
+ shapeRef);
//Line 10
System.out.println();
//Line 11
shapeRef = box;
//Line 12
System.out.println("Line 13: Box:\n"
+ shapeRef);
//Line 13
System.out.println();
//Line 14
}
//end main
//Line 15
}
//Line 16
Sample Run:
Line 10: Rectangle:
Length = 8.0; Width = 5.0
Area = 40.0
Line 13: Box:
Length = 10.0; Width = 7.0; Height = 3.0
Surface Area = 242.0; Volume = 210.0
In the preceding program,
shapeRef
is a reference variable of the
RectangleFigure
type. Because the
class
BoxFigure
is derived from the
class
RectangleFigure
, the
reference variable
shapeRef
can point to an object of the
class
RectangleFigure
or
to an object of the
class
BoxFigure
.
The statement in Line 7 instantiates a
RectangleFigure
object and stores the address of this
object in the reference variable
rectangle
. Similarly, the statement in Line 8 instantiates a
BoxFigure
object and stores the address of this object in the reference variable
box
.
After the statement in Line 9 executes,
shapeRef
points to the object
rectangle
. The
statement in Line 10 executes the method
toString
. Because
shapeRef
points to
an object of the
class
RectangleFigure
, the method
toString
of the
class
RectangleFigure
executes. When the method
toString
of the
class
RectangleFigure
executes, it also executes the method
area
. In this case, the method
area
of the
class
RectangleFigure
executes.
Search WWH ::
Custom Search