Java Reference
In-Depth Information
In this program,
t2
is constructed from
t1
and is, thus, identical. The output is shown
here:
Pay special attention to this
Triangle
constructor:
It receives an object of type
Triangle
and it passes that object (through
super
) to this
TwoDShape
constructor:
The key point is that
TwoDshape( )
is expecting a
TwoDShape
object. However,
Tri-
angle( )
passes it a
Triangle
object. The reason this works is because, as explained, a su-
perclass reference can refer to a subclass object. Thus, it is perfectly acceptable to pass
TwoDShape( )
a reference to an object of a class derived from
TwoDShape
. Because the
TwoDShape( )
constructor is initializing only those portions of the subclass object that are
members of
TwoDShape
, it doesn't matter that the object might also contain other mem-
bers added by derived classes.