Java Reference
In-Depth Information
When to Use Inheritance (continued)
//Perform arithmetic for salaried employee
break;
case 1:
//Perform arithmetic for hourly employee
break;
case 2:
//Perform arithmetic for contractor employee
break;
//and so on if necessary
}
}
And the computePay() method will keep getting longer and longer as different types of
employees arise. Any time you find yourself writing classes that do not know what type they
are, you probably should rethink your design. With inheritance, all of these issues are
avoided.
The common features of employees appear in a parent class. Each different type of
employee is represented by a child class. When a new type of employee such as a con-
tractor comes along, a new child class is written that extends the parent class. None of the
existing code needs to be touched.
This benefit is difficult to achieve with procedural programming and also with poorly
designed OOP applications. To avoid these situations, constantly test your OOP design
against these simple rules: An object “has” an attribute, and an object “does” a behavior.
In our employee example, if it is not true that an employee “has” a salary, an Employee
class should not have a salary field, and we should redesign our program.
The Salary class should have a field to represent the employee's annual
salary because a Salaried employee has a salary. The Hourly class should have
fields to represent the employee's hourly pay and number of hours worked
because these are attributes of an Hourly employee.
The following classes demonstrate what the Salary and Hourly classes might
look like. Look closely at the attributes and behaviors of these two classes. As
with the Employee class, there is something flawed with this design also.
public class Salary
{
public String name;
public String address;
public int SSN;
public int number;
public float salary;
public void mailCheck()
{
Search WWH ::




Custom Search