Java Reference
In-Depth Information
TIP:
(continued)
The line
super
(originalObject);
is an invocation of a constructor for the base class
Employee
. The class
Employee
has no
constructor with a parameter of type
HourlyEmployee
, but
originalObject
is of type
HourlyEmployee
. Fortunately, every object of type
HourlyEmployee
is also of type
Employee
. So, this invocation of
super
is an invocation of the copy constructor for the
class
Employee
.
The fact that every object not only is of its own type but is also of the type of its
ancestor classes simply reflects what happens in the everyday world. An hourly employee
is an employee as well as an hourly employee. This sometimes is referred to as the
“is a”
relationship
: For example, an
HourlyEmployee
is an
Employee
.
Display 7.6 contains a program demonstrating that an
HourlyEmployee
and a
SalariedEmployee
are also
Employee
objects. The method
showEmployee
requires an
argument of type
Employee
. The objects
joe
and
sam
are of type
Employee
because they
are instances of classes derived from the class
Employee
and so they are suitable argu-
ments for
showEmployee
.
“is a”
relationship
■
An Object of a Derived Class Has More than One Type
An object of a derived class has the type of the derived class, and it also has the type of the
base class. More generally, a derived class has the type of every one of its ancestor classes.
So, you can assign an object of a derived class to a variable of any ancestor type (but not the
other way around). You can plug in a derived class object for a parameter of any of its ances-
tor types. More generally, you can use a derived class object anyplace you can use an object
of any of its ancestor types.