Java Reference
In-Depth Information
For example, line 46 could have called
getCommissionRate
and
getGrossSales
to access
CommissionEmployee
's
private
instance variables
commissionRate
and
grossSales
, re-
spectively. Lines 56-58 also could have used appropriate
get
methods to retrieve the values
of the superclass's instance variables.
Inheritance Hierarchy Using
protected
Instance Variables
To enable class
BasePlusCommissionEmployee
to directly access superclass instance vari-
ables
firstName
,
lastName
,
socialSecurityNumber
,
grossSales
and
commissionRate
,
we can declare those members as
protected
in the superclass. As we discussed in
Section 9.3, a superclass's
protected
members are accessible by all subclasses of that su-
perclass. In the new
CommissionEmployee
class, we modified only lines 6-10 of Fig. 9.4
to declare the instance variables with the
protected
access modifier as follows:
protected final
String firstName;
protected final
String lastName;
protected final
String socialSecurityNumber;
protected
double
grossSales;
// gross weekly sales
protected
double
commissionRate;
// commission percentage
The rest of the class declaration (which is not shown here) is identical to that of Fig. 9.4.
We could have declared
CommissionEmployee
's instance variables
public
to enable sub-
class
BasePlusCommissionEmployee
to access them. However, declaring
public
instance
variables is poor software engineering because it allows unrestricted access to the these vari-
ables from any class, greatly increasing the chance of errors. With
protected
instance vari-
ables, the subclass gets access to the instance variables, but classes that are not subclasses and
classes that are not in the same package cannot access these variables directly—recall that
protected
class members are also visible to other classes in the same package.
Class
BasePlusCommissionEmployee
Class
BasePlusCommissionEmployee
(Fig. 9.9) extends the new version of class
Commis-
sionEmployee
with
protected
instance variables.
BasePlusCommissionEmployee
objects
inherit
CommissionEmployee
's
protected
instance variables
firstName
,
lastName
,
so-
cialSecurityNumber
,
grossSales
and
commissionRate
—all these variables are now
pro-
tected
members of
BasePlusCommissionEmployee
. As a result, the compiler does not
generate errors when compiling line 45 of method
earnings
and lines 54-56 of method
toString
. If another class extends this version of class
BasePlusCommissionEmployee
, the
new subclass also can access the
protected
members.
1
// Fig. 9.9: BasePlusCommissionEmployee.java
2
// BasePlusCommissionEmployee inherits protected instance
3
// variables from CommissionEmployee.
4
5
6
public
class
BasePlusCommissionEmployee
extends
CommissionEmployee
{
7
private
double
baseSalary;
// base salary per week
Fig. 9.9
| BasePlusCommissionEmployee
inherits
protected
instance variables from
CommissionEmployee
. (Part 1 of 2.)