Java Reference
In-Depth Information
34
return
socialSecurityNumber;
35
}
36
37
// return String representation of Employee object
38
@Override
39
public
String toString()
40
{
41
return
String.format(
"%s %s%nsocial security number: %s"
,
42
getFirstName(), getLastName(), getSocialSecurityNumber());
43
}
44
45
// abstract method must be overridden by concrete subclasses
public abstract double
earnings();
// no implementation here
46
47
}
// end abstract class Employee
Fig. 10.4
|
Employee
abstract superclass. (Part 2 of 2.)
Why did we decide to declare
earnings
as an
abstract
method? It simply does not
make sense to provide a
specific
implementation of this method in class
Employee
. We
cannot calculate the earnings for a
general
Employee
—we first must know the
specific
type
of
Employee
to determine the appropriate earnings calculation. By declaring this method
abstract
, we indicate that each concrete subclass
must
provide an appropriate
earnings
implementation and that a program will be able to use superclass
Employee
variables to
invoke method
earnings
polymorphically
for any type of
Employee
.
Class
SalariedEmployee
(Fig. 10.5) extends class
Employee
(line 4) and overrides
abstract
method
earnings
(lines 38-42), which makes
SalariedEmployee
a
concrete
class. The class
includes a constructor (lines 9-19) that receives a first name, a last name, a social security
number and a weekly salary; a
set
method to assign a new
nonnegative
value to instance vari-
able
weeklySalary
(lines 22-29); a
get
method to return
weeklySalary
's value (lines 32-
35); a method
earnings
(lines 38-42) to calculate a
SalariedEmployee
's earnings; and a
method
toString
(lines 45-50), which returns a
String
including
"salaried employee: "
followed by employee-specific information produced by superclass
Employee
's
toString
method and
Salaried-Employee
's
getWeeklySalary
method. Class
SalariedEmployee
's
constructor passes the first name, last name and social security number to the
Employee
con-
structor (line 12) to initialize the
private
instance variables of the superclass. Once again,
we've duplicated the
weeklySalary
validation code in the constructor and the
setWeekly-
Salary
method. Recall that more complex validation could be placed in a
static
class meth-
od that's called from the constructor and the
set
method.
Error-Prevention Tip 10.1
We've said that you should not call a class's instance methods from its constructors—you
can call
static
class methods and make the required call to one of the superclass's con-
structors. If you follow this advice, you'll avoid the problem of calling the class's overrid-
able methods either directly or indirectly, which can lead to runtime errors.
Method
earnings
overrides
Employee
's
abstract
method
earnings
to provide a
con-
crete
implementation that returns the
SalariedEmployee
's weekly salary. If we do not