Java Reference
In-Depth Information
Employee information obtained by get methods:
First name is Bob
Last name is Lewis
Social security number is 333-33-3333
Gross sales is 5000.00
Commission rate is 0.04
Base salary is 300.00
Updated employee information obtained by toString:
base-salaried commission employee: Bob Lewis
social security number: 333-33-3333
gross sales: 5000.00
commission rate: 0.04
base salary: 1000.00
Fig. 9.7
| BasePlusCommissionEmployee
test program. (Part 2 of 2.)
Notes on Class
BasePlusCommissionEmployee
Much of class
BasePlusCommissionEmployee
's code (Fig. 9.6) is
similar
, or
identical
, to
that of class
CommissionEmployee
(Fig. 9.4). For example,
private
instance variables
firstName
and
lastName
and methods
setFirstName
,
getFirstName
,
setLastName
and
getLastName
are identical to those of class
CommissionEmployee
. The classes also both
contain
private
instance variables
socialSecurityNumber
,
commissionRate
and
gross-
Sales
, and corresponding
get
and
set
methods. In addition, the
BasePlusCommissionEm-
ployee
constructor is
almost
identical to that of class
CommissionEmployee
, except that
BasePlusCommissionEmployee
's constructor also sets the
baseSalary
. The other addi-
tions to class
BasePlusCommissionEmployee
are
private
instance variable
baseSalary
and methods
setBaseSalary
and
getBaseSalary
. Class
BasePlusCommissionEmployee
's
toString
method is
almost
identical to that of class
CommissionEmployee
except that it
also outputs instance variable
baseSalary
with two digits of precision to the right of the
decimal point.
We literally
copied
code from class
CommissionEmployee
and
pasted
it into class
Base-
PlusCommissionEmployee
, then modified class
BasePlusCommissionEmployee
to include
a base salary and methods that manipulate the base salary. This
“copy-and-paste” approach
is often error prone and time consuming. Worse yet, it spreads copies of the same code
throughout a system, creating code-maintenance problems—changes to the code would
need to be made in multiple classes. Is there a way to “acquire” the instance variables and
methods of one class in a way that makes them part of other classes
without duplicating
code
? Next we answer this question, using a more elegant approach to building classes that
emphasizes the benefits of inheritance.
Software Engineering Observation 9.3
With inheritance, the instance variables and methods that are the same for all the classes
in the hierarchy are declared in a superclass. Changes made to these common features in
the superclass are inherited by the subclass. Without inheritance, changes would need to
be made to
all
the source-code files that contain a
copy
of the code in question.