Java Reference
In-Depth Information
A better design for the Salary and Hourly classes is to take their common
elements and put them in a parent class, leaving the unique elements in the
child classes. For example, the mailCheck() method could appear in the
Employee parent class, and the computePay() method could appear in each of
the child classes. The assumption is that the process of mailing a check is the
same for all employees, but computing their pay is directly affected by how
they are paid.
Employees do not share a common computePay() method. By placing com-
putePay() in each child class, the method will be written twice. This is not
repeating code, though, because computePay() in Salary is quite different than
computePay() in Hourly.
The is a Relationship
The is a relationship is a simple but powerful rule for testing if your inheri-
tance is a good design. Whenever you use inheritance, you should be able to
say that a child is a parent. If this statement is true, your inheritance is likely a
good design.
For example, it is true that a salaried employee is an employee. Similarly, an
hourly employee is an employee; therefore, it is reasonable that the Salary and
Hourly classes extend the Employee class.
Let's look at an example where inheritance is not a good idea. Suppose that
you have a Date class that represents a calendar date, and you want to use that
class to keep track of the date when an employee was hired.
Because inheritance has so many benefits, you decide to have the Employee
class extend the Date class. When you instantiate an Employee object, you will
also get a Date object for storing the employee's hire date; however, is it true
that an employee is a date? The is a relationship clearly fails here. Although the
result might work for us, an Employee class inheriting from a Date class is not
a good design and should not be used.
The solution to the improper use of inheritance with the Employee and
Date classes is to realize that an employee has a hire date, not that an
employee is a hire date. If an object has an attribute, the attribute should
be a field in the class. The Employee class should add a field of type Date
to represent the hire date of an employee, as opposed to extending the
Date class.
Search WWH ::




Custom Search