Java Reference
In-Depth Information
the child class overrode the definition it inherited). The following invocation calls
the
move
method, but the particular version of the method it calls is determined
at run time:
creature.move();
When this line is executed, if
creature
currently refers to an
Animal
object, the
move
method of the
Animal
class is invoked. Likewise, if
creature
currently refers
to a
Mammal
object, the
Mammal
version of
move
is invoked. Likewise if it currently
refers to a
Horse
object.
Of course, since
Animal
and
Mammal
represent general concepts, they may be
defined as abstract classes. This situation does not eliminate the ability to have
polymorphic references. Suppose the
move
method in the
Mammal
class is abstract
and is given unique definitions in the
Horse
,
Dog
, and
Whale
classes (all derived
from
Mammal
). A
Mammal
reference variable can be used to refer to any objects cre-
ated from any of the
Horse
,
Dog
, and
Whale
classes, and can be used to execute
the
move
method on any of them.
Let's look at another situation. Consider the class hierarchy shown in Figure 10.1.
The classes in it represent various types of employees that might be employed at
a particular company. Let's explore an example that uses this hierarchy to pay a
set of employees of various types.
The
Firm
class shown in Listing 10.1 contains a
main
driver that creates a
Staff
of employees and invokes the
payday
method to pay them all. The program
output includes information about each employee and how much each is paid (if
anything).
The
Staff
class shown in Listing 10.2 maintains an array of objects that repre-
sent individual employees of various kinds. Note that the array is declared to hold
StaffMember
references, but it is actually filled with objects created from several
other classes, such as
Executive
and
Employee
. These classes are all descendants
of the
StaffMember
class, so the assignments are valid. The
staffList
array is
filled with polymorphic references.
The
payday
method of the
Staff
class scans through the list of employees,
printing their information and invoking their
pay
methods to determine how
much each employee should be paid. The invocation of the
pay
method is poly-
morphic, because each class has its own version of the
pay
method.
The
StaffMember
class shown in Listing 10.3 is abstract. It does not represent
a particular type of employee and is not intended to be instantiated. Rather,
it serves as the ancestor of all employee classes and contains information that
applies to all employees. Each employee has a name, address, and phone number,
so variables to store these values are declared in the
StaffMember
class and are
inherited by all descendants.
VideoNote
Exploring the Firm
program.
Search WWH ::
Custom Search