Java Reference
In-Depth Information
are visible to all classes in the same package as the class containing the
protected
mem-
bers—this is not always desirable.
Software Engineering Observation 9.7
Use the
protected
access modifier when a superclass should provide a method only to its
subclasses and other classes in the same package, but not to other clients.
Software Engineering Observation 9.8
Declaring superclass instance variables
private
(as opposed to
protected
) enables the
superclass implementation of these instance variables to change without affecting subclass
implementations.
Error-Prevention Tip 9.2
When possible, do not include
protected
instance variables in a superclass. Instead, in-
clude non-
private
methods that access
private
instance variables. This will help ensure
that objects of the class maintain consistent states.
Inheritance Hierarchy Using
private
Instance Variables
Let's reexamine our hierarchy once more, this time using good software engineering prac-
tices.
Class
CommissionEmployee
Class
CommissionEmployee
(Fig. 9.10) declares instance variables
firstName
,
lastName
,
socialSecurityNumber
,
grossSales
and
commissionRate
as
private
(lines 6-10) and
provides
public
methods
getFirstName
,
getLastName
,
getSocialSecurityNumber
,
set-
GrossSales
,
getGrossSales
,
setCommissionRate
,
getCommissionRate
,
earnings
and
toString
for manipulating these values. Methods
earnings
(lines 87-90) and
toString
(lines 93-101) use the class's
get
methods to obtain the values of its instance variables. If
we decide to change the names of the instance variables, the
earnings
and
toString
dec-
larations will
not
require modification—only the bodies of the
get
and
set
methods that di-
rectly manipulate the instance variables will need to change. These changes occur solely
within the superclass—no changes to the subclass are needed.
Localizing the effects of chang-
es
like this is a good software engineering practice.
1
// Fig. 9.10: CommissionEmployee.java
2
// CommissionEmployee class uses methods to manipulate its
3
// private instance variables.
4
public
class
CommissionEmployee
5
{
6
private final
String firstName;
private final
String lastName;
private final
String socialSecurityNumber;
private
double
grossSales;
// gross weekly sales
private
double
commissionRate;
// commission percentage
7
8
9
10
Fig. 9.10
| CommissionEmployee
class uses methods to manipulate its
private
instance
variables. (Part 1 of 3.)