Java Reference
In-Depth Information
goodPower = 8
respect = 7
name = Peter Parker
super object
object for SpiderMan
FIGURE 8.3:
Class inheritance and super object.
Although similar, there are three subtle differences between inheritance and con-
tainment. First, they use very distinct syntax. Second, inheritance guarantees the
presence of exactly one super object in the subclass. Conversely, the value of the con-
tained object can be equal to
null
. Lastly, as we will see later on in this chapter, we
can use polymorphism with inheritance. However, it is impossible to use polymorphism
with class containment alone.
8.3 Multiple Inheritance
Java does not support multiple inheritance. In other words, a class cannot inherit from
more than one superclass. This is the reason the
super
reference is not ambiguous. If a
class could inherit from more than one superclasses, then we could not speak of a unique
superclass and the
super
keyword will be ambiguous.
We should always use inheritance instead of containment when applicable. For example,
the
Student
class should inherit from the
Person
class and not contain the
Person
class.
However, sometimes it is warranted to use class containment as a substitute for class in-
heritance. Consider, for example, the design from Figure 8.4. Both teachers and students
inherit from the
Person
class. However, a teaching assistant is both a student and a teacher
and therefore multiple inheritance is needed here. However, Java does not support multiple
inheritance.
One way to represent multiple inheritance in Java is by using class containment in its
place. Here is one possible implementation of the above design.
class
Person
{
...
}
class
Teacher
extends
Person
{