THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1

them?


3.12. Single Inheritance versus Multiple Inheritance


A new class can extend exactly one superclass, a model known as single inheritance. Extending a class means
that the new class inherits not only its superclass's contract but also its superclass's implementation. Some
object-oriented languages employ multiple inheritance, in which a new class can have two or more
superclasses.


Multiple inheritance is useful when you want a new class to combine multiple contracts and inherit some, or
all, of the implementation of those contracts. But when there is more than one superclass, problems arise when
a superclass's behavior is inherited in two ways. Assume, for a moment, the following type tree:


This is commonly called diamond inheritance, and there is nothing wrong with it. Many legitimate designs
show this structure. The problems exist in the inheritance of implementation, when W's implementation stores
some state. If class W had, for example, a public field named goggin, and if you had a reference to an object
of type Z called zref, what would zref.goggin refer to? It might refer to X's copy of goggin, or it
might refer to Y's copy, or X and Y might share a single copy of goggin because Z is really only a W once
even though it is both an X and a Y. Resolving such issues is non-trivial and complicates the design and use of
class hierarchies. To avoid such issues, the Java programming language uses the single-inheritance model of
object-oriented programming.


Single inheritance precludes some useful and correct designs. The problems of multiple inheritance arise from
multiple inheritance of implementation, but in many cases multiple inheritance is used to inherit a number of
abstract contracts and perhaps one concrete implementation. Providing a means to inherit an abstract contract
without inheriting an implementation allows the typing benefits of multiple inheritance without the problems
of multiple implementation inheritance. The inheritance of an abstract contract is termed interface inheritance.
The Java pro gramming language supports interface inheritance by allowing you to declare an interface
typethe subject of the next chapter.


When we are planning for posterity, we ought to remember that virtue is not hereditary.

Thomas Paine

Chapter 4. Interfaces


"Conducting" is when you draw "designs" in the nowherewith your stick, or with your
handswhich are interpreted as "instructional messages" by guys wearing bow ties who wish
they were fishing.

Frank Zappa

The fundamental unit of programming in the Java programming language is the class, but the fundamental
unit of object-oriented design is the type. While classes define types, it is very useful and powerful to be able

Free download pdf