Java Reference
In-Depth Information
Single versus Multiple Inheritance
Some OOP languages (such as C++) allow a child class to have more than one
parent; however, this is not allowed in Java. A Java class can only have one par-
ent. For example, the Salary class cannot extend both the Employee class and
a Manager class. Multiple inheritance is not allowed in Java.
One of the goals of the Java language was to create an OOP language that
was simple to use and understand. Multiple inheritance is one of those
capabilities that only tends to add confusion to a language.
In terms of design issues, there are no situations where multiple inheritance
is the only option. (Some may argue that it is needed at times, but I have yet to
be convinced of this by anyone who has attempted to sway me with a specific
example.) Therefore, there is no need to waste time going into the details of
why multiple inheritance is not a requirement of OOP. We can simply appreci-
ate the fact that when learning Java we do not need to bother ourselves with
figuring out the many details and issues of multiple inheritance.
Be aware of what I said about multiple inheritance. I said a Java class can
only have one parent. However, this does not mean a class cannot have a
grandparent, great grandparent, and so on up the hierarchy tree. Keep
reading!
A Java class can have a parent class, and that parent class can have a parent,
and so on. This hierarchy can continue as long as you want.
For example, the Salary class discussed earlier extends the Employee class.
The Salary class can also be a parent class. Any child classes of Salary inherit
the fields and methods of Salary and Employee.
Suppose that you determine that a class is needed to represent part-time
salaried employees, who have an annual salary but must keep track of the
hours they work. Then a new class named PartTimeSalary can be written that
extends the Salary class.
This results in the PartTimeSalary class being a child of Salary, and Salary
being a child of Employee. A PartTimeSalary object inherits everything from
Salary and Employee.
The following class shows the definition of PartTimeSalary. The extends
keyword is used to extend Salary, but you do not specify any inheritance with
Employee. The compiler and JVM know that Salary extends Employee.
public class PartTimeSalary extends Salary
{
public int hoursWorked;
public int getHoursWorked()
Search WWH ::




Custom Search