Java Reference
In-Depth Information
This section reexamines the
CommissionEmployee
-
BasePlusCommissionEmployee
hierar-
chy that we explored throughout Section 9.4. Now we use an abstract method and poly-
morphism to perform payroll calculations based on an enhanced employee inheritance
hierarchy that meets the following requirements:
A company pays its employees on a weekly basis. The employees are of four types: Salaried
employees are paid a fixed weekly salary regardless of the number of hours worked, hourly
employees are paid by the hour and receive overtime pay (i.e., 1.5 times their hourly sal-
ary rate) for all hours worked in excess of 40 hours, commission employees are paid a per-
centage of their sales and base-salaried commission employees receive a base salary plus a
percentage of their sales. For the current pay period, the company has decided to reward
salaried-commission employees by adding 10% to their base salaries. The company
wants you to write an application that performs its payroll calculations polymorphically.
We use
abstract
class
Employee
to represent the general concept of an employee. The
classes that extend
Employee
are
SalariedEmployee
,
CommissionEmployee
and
Hourly-
Employee
. Class
BasePlusCommissionEmployee
—which extends
CommissionEmployee
—
represents the last employee type. The UML class diagram in Fig. 10.2 shows the inheri-
tance hierarchy for our polymorphic employee-payroll application. Abstract class name
Employee
is italicized—a convention of the UML.
Employee
SalariedEmployee
CommissionEmployee
HourlyEmployee
BasePlusCommissionEmployee
Fig. 10.2
|
Employee
hierarchy UML class diagram.
Abstract superclass
Employee
declares the “interface” to the hierarchy—that is, the set
of methods that a program can invoke on all
Employee
objects. We use the term “interface”
here in a
general
sense to refer to the various ways programs can communicate with objects
of
any
Employee
subclass. Be careful not to confuse the general notion of an “interface”
with the formal notion of a Java interface, the subject of Section 10.9. Each employee,
regardless of the way his or her earnings are calculated, has a first name, a last name and a
social security number, so
private
instance variables
firstName
,
lastName
and
social-
SecurityNumber
appear in abstract superclass
Employee
.
The diagram in Fig. 10.3 shows each of the five classes in the hierarchy down the left
side and methods
earnings
and
toString
across the top. For each class, the diagram
shows the desired results of each method. We do not list superclass
Employee
's
get
methods
because they're
not
overridden in any of the subclasses—each of these methods is inherited
and used “as is” by each subclass.