Java Reference
In-Depth Information
27
28
this
.baseSalary = baseSalary;
29
}
30
31
// return base salary
32
public double
getBaseSalary()
33
{
34
return
baseSalary;
35
}
36
37
// calculate earnings; override method earnings in CommissionEmployee
@Override
public double
earnings()
{
return
getBaseSalary() +
super
.earnings();
}
38
39
40
41
42
43
44
// return String representation of BasePlusCommissionEmployee object
@Override
public
String toString()
{
return
String.format(
"%s %s; %s: $%,.2f"
,
"base-salaried"
,
super
.toString(),
"base salary"
, getBaseSalary());
}
45
46
47
48
49
50
51
52
}
// end class BasePlusCommissionEmployee
Fig. 10.8
|
BasePlusCommissionEmployee
class extends
CommissionEmployee
. (Part 2 of 2.)
Downcasting
To test our
Employee
hierarchy, the application in Fig. 10.9 creates an object of each of the
four
concrete
classes
SalariedEmployee
,
HourlyEmployee
,
CommissionEmployee
and
Base-
PlusCommissionEmployee
. The program manipulates these objects
nonpolymorphically
, via
variables of each object's own type, then
polymorphically
, using an array of
Employee
vari-
ables. While processing the objects polymorphically, the program increases the base salary
of each
BasePlusCommissionEmployee
by 10%—this requires
determining the object's type
at execution time
. Finally, the program polymorphically determines and outputs the
type
of
each object in the
Employee
array. Lines 9-18 create objects of each of the four concrete
Employee
subclasses. Lines 22-30 output the
String
representation and earnings of each
of these objects
nonpolymorphically
. Each object's
toString
method is called
implicitly
by
printf
when the object is output as a
String
with the
%s
format specifier.
1
// Fig. 10.9: PayrollSystemTest.java
2
// Employee hierarchy test program.
3
4
public class
PayrollSystemTest
5
{
Fig. 10.9
|
Employee
hierarchy test program. (Part 1 of 4.)