Java Reference
In-Depth Information
implement
earnings
, class
SalariedEmployee
must be declared
abstract
—otherwise,
class
SalariedEmployee
will not compile. Of course, we want
SalariedEmployee
to be a
concrete
class in this example.
Method
toString
(lines 45-50) overrides
Employee
method
toString
. If class
Sala-
riedEmployee
did
not
override
toString
,
SalariedEmployee
would have inherited the
Employee
version of
toString
. In that case,
SalariedEmployee
's
toString
method would
simply return the employee's full name and social security number, which does
not
ade-
quately represent a
SalariedEmployee
. To produce a complete
String
representation of a
SalariedEmployee
, the subclass's
toString
method returns
"salaried employee: "
fol-
lowed by the superclass
Employee
-specific information (i.e., first name, last name and social
security number) obtained by invoking the
superclass's
toString
method (line 49)—this is a
nice example of
code reuse
. The
String
representation of a
SalariedEmployee
also contains
the employee's weekly salary obtained by invoking the class's
getWeeklySalary
method.
Class
HourlyEmployee
(Fig. 10.6) also extends
Employee
(line 4). The class includes a con-
structor (lines 10-25) that receives a first name, a last name, a social security number, an
hourly wage and the number of hours worked. Lines 28-35 and 44-51 declare
set
methods
that assign new values to instance variables
wage
and
hours
, respectively. Method
setWage
(lines 28-35) ensures that
wage
is
nonnegative
, and method
setHours
(lines 44-51) ensures
that the value of
hours
is between 0 and 168 (the total number of hours in a week) inclusive.
Class
HourlyEmployee
also includes
get
methods (lines 38-41 and 54-57) to return the val-
ues of
wage
and
hours
, respectively; a method
earnings
(lines 60-67) to calculate an
Hour-
lyEmployee
's earnings; and a method
toString
(lines 70-76), which returns a
String
containing the employee's type (
"hourly employee: "
) and the employee-specific informa-
tion. The
HourlyEmployee
constructor, like the
SalariedEmployee
constructor, passes the
first name, last name and social security number to the superclass
Employee
constructor
(line 13) to initialize the
private
instance variables. In addition, method
toString
calls
su-
perclass
method
toString
(line 74) to obtain the
Employee
-specific information (i.e., first
name, last name and social security number)—this is another nice example of
code reuse
.
1
// Fig. 10.6: HourlyEmployee.java
2
// HourlyEmployee class extends Employee.
3
4
public class
HourlyEmployee
extends
Employee
5
{
6
private double
wage;
// wage per hour
7
private double
hours;
// hours worked for week
8
9
// constructor
10
public
HourlyEmployee(String firstName, String lastName,
11
String socialSecurityNumber,
double
wage,
double
hours)
12
{
13
super
(firstName, lastName, socialSecurityNumber);
14
Fig. 10.6
|
HourlyEmployee
class extends
Employee
. (Part 1 of 3.)