Java Reference
In-Depth Information
Class
BasePlusCommissionEmployee
(Fig. 10.8) extends class
CommissionEmployee
(line
4) and therefore is an
indirect
subclass of class
Employee
. Class
BasePlusCommission-
Employee
has a constructor (lines 9-20) that receives a first name, a last name, a social se-
curity number, a sales amount, a commission rate and a base salary. It then passes all of
these except the base salary to the
CommissionEmployee
constructor (lines 13-14) to ini-
tialize the superclass instance variables.
BasePlusCommissionEmployee
also contains a
set
method (lines 23-29) to assign a new value to instance variable
baseSalary
and a
get
method (lines 32-35) to return
baseSalary
's value. Method
earnings
(lines 38-42) cal-
culates a
BasePlusCommissionEmployee
's earnings. Line 41 in method
earnings
calls
su-
perclass
CommissionEmployee
's
earnings
method to calculate the commission-based
portion of the employee's earnings—this is another nice example of
code reuse
.
Base-
PlusCommissionEmployee
's
toString
method (lines 45-51) creates a
String
representa-
tion of a
BasePlusCommissionEmployee
that contains
"base-salaried"
, followed by the
String
obtained by invoking
superclass
CommissionEmployee
's
toString
method (line
49), then the base salary. The result is a
String
beginning with
"base-salaried
commis-
sion
employee"
followed by the rest of the
BasePlusCommissionEmployee
's information.
Recall that
CommissionEmployee
's
toString
obtains the employee's first name, last name
and social security number by invoking the
toString
method of its
superclass
(i.e.,
Employ-
ee
)—yet another example of
code reuse
.
BasePlusCommissionEmployee
's
toString
initi-
ates a
chain of method calls
that span all three levels of the
Employee
hierarchy.
1
// Fig. 10.8: BasePlusCommissionEmployee.java
2
// BasePlusCommissionEmployee class extends CommissionEmployee.
3
4
public class
BasePlusCommissionEmployee
extends
CommissionEmployee
5
{
6
private double
baseSalary;
// base salary per week
7
8
// constructor
9
public
BasePlusCommissionEmployee(String firstName, String lastName,
10
String socialSecurityNumber,
double
grossSales,
11
double
commissionRate,
double
baseSalary)
12
{
13
super
(firstName, lastName, socialSecurityNumber,
14
grossSales, commissionRate);
15
16
if
(baseSalary <
0.0
)
// validate baseSalary
17
throw new
IllegalArgumentException(
"Base salary must be >= 0.0"
);
18
19
this
.baseSalary = baseSalary;
20
}
21
22
// set base salary
23
public void
setBaseSalary(
double
baseSalary)
24
{
25
if
(baseSalary <
0.0
)
// validate baseSalary
26
throw new
IllegalArgumentException(
"Base salary must be >= 0.0"
);
Fig. 10.8
|
BasePlusCommissionEmployee
class extends
CommissionEmployee
. (Part 1 of 2.)