Java Reference
In-Depth Information
System.out.println(“Mailing a check to “ + name
+ “ “ + address);
}
public float computePay()
{
return (float) salary/52.0;
}
}
public class Hourly
{
public String name;
public String address;
public int SSN;
public int number;
public float hourlyRate;
public float hoursWorked
public void mailCheck()
{
System.out.println(“Mailing a check to “ + name
+ “ “ + address);
}
public float computePay()
{
return (float) hoursWorked * hourlyRate;
}
}
The Salary and Hourly classes demonstrate the need for inheritance.
Although Salary and Hourly employees are different types, they are
not entirely different. In fact, the two types of employees have a lot in
common, as seen by the repetition of fields and methods in these two
classes. Using inheritance will improve this design considerably, so keep
in mind that writing two separate classes for the two different types of
employees is not yet a satisfactory solution.
As you can see, the Salary and Hourly classes are repeating code. Salary and
hourly employees are still employees, and there is a lot of information in com-
mon between the two. Inheritance can be used in this situation not only to
avoid repeating code, but also to create a program design that allows for bet-
ter maintenance and code changes later.
When two or more classes are different but share similar features, take the
common elements of the classes and put them in a parent class. The classes can
extend this parent class, thereby inheriting all the features of the parent, yet the
different features can remain in each child class.