Java Reference
In-Depth Information
68
69
// return String representation of HourlyEmployee object
@Override
public
String toString()
{
return
String.format(
"hourly employee: %s%n%s: $%,.2f; %s: %,.2f"
,
super
.toString(),
"hourly wage"
, getWage(),
"hours worked"
, getHours());
}
70
71
72
73
74
75
76
77
}
// end class HourlyEmployee
Fig. 10.6
|
HourlyEmployee
class extends
Employee
. (Part 3 of 3.)
Class
CommissionEmployee
(Fig. 10.7) extends class
Employee
(line 4). The class includes a
constructor (lines 10-25) that takes a first name, a last name, a social security number, a sales
amount and a commission rate;
set
methods (lines 28-34 and 43-50) to assign valid new val-
ues to instance variables
commissionRate
and
grossSales
, respectively;
get
methods (lines
37-40 and 53-56) that retrieve the values of these instance variables; method
earnings
(lines 59-63) to calculate a
CommissionEmployee
's earnings; and method
toString
(lines
66-73), which returns the employee's type, namely,
"commission
employee: "
and employ-
ee-specific information. The constructor also passes the first name, last name and social se-
curity number to
superclass
Employee
's constructor (line 14) to initialize
Employee
's
private
instance variables. Method
toString
calls
superclass
method
toString
(line 70) to obtain the
Employee
-specific information (i.e., first name, last name and social security number).
1
// Fig. 10.7: CommissionEmployee.java
2
// CommissionEmployee class extends Employee.
3
4
public class
CommissionEmployee
extends
Employee
5
{
6
private double
grossSales;
// gross weekly sales
7
private double
commissionRate;
// commission percentage
8
9
// constructor
10
public
CommissionEmployee(String firstName, String lastName,
11
String socialSecurityNumber,
double
grossSales,
12
double
commissionRate)
13
{
14
super
(firstName, lastName, socialSecurityNumber);
15
16
if
(commissionRate <=
0.0
|| commissionRate >=
1.0
)
// validate
17
throw new
IllegalArgumentException(
18
"Commission rate must be > 0.0 and < 1.0")
;
19
20
if
(grossSales <
0.0
)
// validate
21
throw new
IllegalArgumentException(
"Gross sales must be >= 0.0"
);
22
Fig. 10.7
|
CommissionEmployee
class extends
Employee
. (Part 1 of 2.)