Java Reference
In-Depth Information
Inheritance is arguably the single most important aspect of OOP. The ability
to create a new class as an extension of an existing class has many benefits,
including the important concepts of polymorphsism and abstraction, discussed
in Chapter 8, “Polymorphism and Abstraction.”
Inheritance is best explained with an example. Recall the example where a
program is needed to pay employees of a company every week. One obvious
object in this problem domain is the employee, and it was decided that an
Employee class is to be written.
Consider the following Employee class, which includes attributes for the
employee's name, address, SSN, number, and salary. The methods are compute-
Pay() and mailCheck().
public class Employee
{
public String name;
public String address;
public int SSN;
public int number;
public float salary;
public void mailCheck()
{
System.out.println(“Mailing a check to “ + name + “ “ + address);
}
public float computePay()
{
return (float) salary/52.0;
}
}
The design of the Employee class might seem fine initially. An employee has
a name, address, and number, and we want the employee objects to compute
their pay and mail a check.
Keep in mind that we are using the Employee class in the context of paying
employees. Is it true that every employee has a salary? What about employees
who are paid by the hour, or contractors who are paid by the day, or those in
other situations where an employee is not paid by an annual salary? Perhaps
the Employee class needs further analysis.
The first mistake in the Employee class is adding a field of type salary. Does
every employee have a salary? If the answer is no, the Employee class should
not have a field of type salary.
What do we do instead? We need to realize that although employees are
objects in our problem domain, there are actually two different types of
employee objects: salaried employees and hourly employees. Therefore, we
should write two classes: Salary and Hourly.
Search WWH ::




Custom Search