Java Reference
In-Depth Information
9.4.3 Creating a
CommissionEmployee
-
Now we declare class
BasePlusCommissionEmployee
(Fig. 9.8) to
extend
class
Commis-
sionEmployee
(Fig. 9.4). A
BasePlusCommissionEmployee
object
is a
CommissionEm-
ployee
, because inheritance passes on class
CommissionEmployee
's capabilities. Class
BasePlusCommissionEmployee
also has instance variable
baseSalary
(Fig. 9.8, line 6).
Keyword
extends
(line 4) indicates inheritance.
BasePlusCommissionEmployee
inherits
CommissionEmployee
's instance variables and methods.
Software Engineering Observation 9.4
At the design stage in an object-oriented system, you'll often find that certain classes are
closely related. You should “factor out” common instance variables and methods and place
them in a superclass. Then use inheritance to develop subclasses, specializing them with
capabilities beyond those inherited from the superclass.
Software Engineering Observation 9.5
Declaring a subclass does not affect its superclass's source code. Inheritance preserves the
integrity of the superclass.
Only
CommissionEmployee
's
public
and
protected
members are directly accessible
in the subclass. The
CommissionEmployee
constructor is
not
inherited. So, the
public
BasePlusCommissionEmployee
services include its constructor (lines 9-23),
public
methods inherited from
CommissionEmployee
, and methods
setBaseSalary
(lines 26-
33),
getBaseSalary
(lines 36-39),
earnings
(lines 42-47) and
toString
(lines 50-60).
Methods
earnings
and
toString
override
the corresponding methods in class
Commis-
sionEmployee
because their superclass versions do not properly calculate a
BasePlusCom-
missionEmployee
's earnings or return an appropriate
String
representation, respectively.
1
// Fig. 9.8: BasePlusCommissionEmployee.java
2
// private superclass members cannot be accessed in a subclass.
3
4
5
public
class
BasePlusCommissionEmployee
extends
CommissionEmployee
{
6
private
double
baseSalary;
// base salary per week
7
8
// six-argument constructor
9
public
BasePlusCommissionEmployee(String firstName, String lastName,
10
String socialSecurityNumber,
double
grossSales,
11
double
commissionRate,
double
baseSalary)
12
{
13
// explicit call to superclass CommissionEmployee constructor
super
(firstName, lastName, socialSecurityNumber,
grossSales, commissionRate);
14
15
16
17
// if baseSalary is invalid throw exception
18
if
(baseSalary <
0.0
)
19
throw new
IllegalArgumentException(
20
"Base salary must be >= 0.0"
);
21
Fig. 9.8
| private
superclass members cannot be accessed in a subclass. (Part 1 of 3.)