Multiple inheritance
Multiple inheritance is a feature of some object-oriented computer programming languages in which a class can inherit characteristics and features from more than one superclass. It is distinct to single inheritance, where a class may only inherit from one particular superclass.
Languages that support multiple inheritance include C++, Common Lisp via the Common Lisp Object System, Perl and Python.
Multiple inheritance has been a touchy issue for many years, with opponents pointing to its increased complexity and ambiguity in situations such as the "diamond problem", where it may be ambiguous as to which superclass a particular feature is inherited from if more than one superclass implements said feature. This can be addressed in various ways, including using virtual inheritance.[1]
Contents |
Details
In object-oriented programming (OOP), inheritance describes a relationship between two types, or classes, of objects in which one is said to be a subtype or child of the other. The child inherits features of the parent, allowing for shared functionality. For example, one might create a variable class Mammal with features such as eating, reproducing, etc.; then define a subtype Cat that inherits those features without having to explicitly program them, while adding new features like chasing mice.
Multiple inheritance allows programmers to use more than one totally orthogonal hierarchy simultaneously, such as allowing Cat to inherit from Cartoon character and Pet and Mammal and access features from within all of those classes. Lack of multiple inheritance often results in a very awkwardly mixed hierarchy, or forces functionality to be rewritten in more than one place, with attendant maintenance problems.
Implementations
Languages that support multiple inheritance include: C++, Common Lisp (via Common Lisp Object System (CLOS)), EuLisp (via The EuLisp Object System TELOS), Curl, Dylan, Eiffel, Logtalk, Object REXX, Scala (via use of mixin classes), OCaml, Perl, Perl 6, Python, and Tcl (via Incremental Tcl (Incr Tcl)).[2]
Some object-oriented languages, such as C#, Java, and Ruby implement single inheritance, although protocols, or interfaces, provide some of the functionality of true multiple inheritance.
PHP uses traits classes to inherit multiple functions.
The diamond problem
The "diamond problem" (sometimes referred to as the "deadly diamond of death"[3]) is an ambiguity that arises when two classes B and C inherit from A, and class D inherits from both B and C. If D calls a method defined in A (and does not override the method), and B and C have overridden that method differently, then from which class does it inherit: B, or C?
For example, in the context of GUI software development, a class Button
may inherit from both classes Rectangle
(for appearance) and Clickable
(for functionality/input handling), and classes Rectangle
and Clickable
both inherit from the Object
class. Now if the equals
method is called for a Button
object and there is no such method in the Button
class but there is an overridden equals
method in both Rectangle
and Clickable
, which method should be eventually called?
It is called the "diamond problem" because of the shape of the class inheritance diagram in this situation. In this article, class A is at the top, both B and C separately beneath it, and D joins the two together at the bottom to form a diamond shape.
Mitigation
Languages have different ways of dealing with these problems of repeated inheritance.
- C++ by default follows each inheritance path separately, so a
D
object would actually contain two separateA
objects, and uses ofA
's members have to be properly qualified. If the inheritance fromA
toB
and the inheritance fromA
toC
are both marked "virtual
" (for example, "class B : virtual public A
"), C++ takes special care to only create oneA
object, and uses ofA
's members work correctly. If virtual inheritance and nonvirtual inheritance are mixed, there is a single virtualA
and a nonvirtualA
for each nonvirtual inheritance path toA
. C++ requires stating explicitly which parent class the feature to be used is invoked from i.e. "Worker::Human.Age". C++ does not support explicit repeated inheritance since there would be no way to qualify which superclass to use. C++ also allows a single instance of the multiple class to be created via the virtual inheritance mechanism (i.e. "Worker::Human" and "Musician::Human" will reference the same object). - Common Lisp attempts to provide both reasonable default behavior and the ability to override it. By default, the method with the most specific argument classes is chosen; then in the order in which parent classes are named in the subclass definition. However, the programmer can override this, by giving a specific method resolution order or stating a rule for combining methods.
- Curl allows only classes that are explicitly marked as shared to be inherited repeatedly. Shared classes must define a secondary constructor for each regular constructor in the class. The regular constructor is called the first time the state for the shared class is initialized through a subclass constructor, and the secondary constructor will be invoked for all other subclasses.
- In Eiffel, the ancestors' methods to use are specified explicitly with select and rename directives. This allows the methods of the base class to be shared between its descendants or to even give each of them a separate copy of the base class. Eiffel allows explicitly joining or separating features that are being inherited from superclasses. Eiffel will automatically join features together, if they have the same name and implementation. The class writer has the option to rename the inherited features to separate them. Eiffel also allows explicit repeated inheritance such as A: B, B.
- JavaFX Script in version 1.2 allows multiple inheritance through the use of mixins. In case of conflict, the compiler prohibits the direct usage of the ambiguous variable or function. Each inherited member can still be accessed by casting the object to the mixin of interest, e.g.
(individual as Person).printInfo();
. - In Lisp, the Common Lisp Object System allows full control of the method combination. The metaobject protocol gives a means to modify the inheritance, dynamic dispatch, class instantiation, and other internal mechanisms without affecting the stability of the system.
- Logtalk supports both interface and implementation multi-inheritance, allowing the declaration of method aliases that provide both renaming and access to methods that would be masked out by the default conflict resolution mechanism.
- In OCaml, parent classes are specified individually in the body of the class definition. Methods (and attributes) are inherited in the same order, with each newly inherited method overriding any existing methods. OCaml chooses the last matching definition of a class inheritance list to resolve which method implementation to use under ambiguities. To override the default behavior, one simply qualifies a method call with the desired class definition.
- Perl uses the list of classes to inherit from as an ordered list. The compiler uses the first method it finds by depth-first searching of the superclass list or using the C3 linearization of the class hierarchy. Various extensions provide alternative class composition schemes. The order of inheritance affects the class semantics. In the above ambiguity, class
B
and its ancestors would be checked before classC
and its ancestors, so the method inA
would be inherited throughB
. This is shared with Io and Picolisp. In Perl, this behavior can be overridden using themro
or other modules to use C3 linearization or other algorithms. - Python has the same structure as Perl, but unlike Perl includes it in the syntax of the language. The order of inheritance affects the class semantics. Python had to deal with this upon the introduction of new-style classes, all of which have a common ancestor,
object
. Python creates a list of a classes using the C3 linearization algorithm. That algorithm enforces two constraints: children precede their parents and if a class inherits from multiple classes, they are kept in the order specified in the tuple of base classes. Thus, the method resolution order is:D
,B
,C
,A
.[4][5] - Scala allows multiple instantiation of traits, which allows for multiple inheritance by adding a distinction between the class hierarchy and the trait hierarchy. A class can only inherit from a single class, but can mix-in as many traits as desired. Scala resolves method names using a right-first depth-first search of extended 'traits', before eliminating all but the last occurrence of each module in the resulting list. So, the resolution order is: [
D
,C
,A
,B
,A
], which reduces down to [D
,C
,B
,A
]. - Tcl allows multiple parent classes- their serial affects the name resolution for class members.[6]
Languages that allow only single inheritance, where a class can only derive from one base class, do not have the diamond problem. The reason for this is that such languages have at most one implementation of any method at any level in the inheritance chain regardless of the repetition or placement of methods. Typically these languages allow classes to implement multiple protocols, called interfaces in Java. These protocols define methods but do not provide concrete implementations. This strategy has been used by ActionScript, C#, D, Java, Nemerle, Object Pascal (Delphi), Objective-C, Ruby and Smalltalk. All but Smalltalk allow classes to implement multiple protocols.
Moreover, languages such as Ada, Objective-C, C#, Delphi/Free Pascal and Java allow multiple-inheritance of interfaces (called protocols in Objective-C). Interfaces are like abstract base classes that specify method signatures without implementing any behavior. ("Pure" interfaces such as Java's do not permit any implementation or instance data in the interface.) Nevertheless, even when several interfaces declare the same method signature, as soon as that method is implemented (defined) anywhere in the inheritance chain, it overrides any implementation of that method in the chain above it (in its superclasses). Hence, at any given level in the inheritance chain, there can be at most one implementation of any method. Thus, single-inheritance method implementation does not exhibit the Diamond Problem even with multiple-inheritance of interfaces.
See also
References
- ^ Traits: Composable Units of Behavior
- ^ Tcl Advocacy
- ^ Martin, Robert C. (1997-03-09), Java and C++: A critical comparison, http://objectmentor.com/resources/articles/javacpp.pdf
- ^ http://www.python.org/download/releases/2.2.3/descrintro/#mro
- ^ http://rhettinger.wordpress.com/2011/05/26/super-considered-super/
- ^ Tcl Manual:class
Further reading
- Stroustrup, Bjarne (1999). Multiple Inheritance for C++. Proceedings of the Spring 1987 European Unix Users Group Conference
- Object-Oriented Software Construction, Second Edition, by Bertrand Meyer, Prentice Hall, 1997, ISBN 0-13-629155-4
- Eddy Truyen, Wouter Joosen, Bo Nørregaard Jørgensen, Pierre Verbaeten (2004). "A Generalization and Solution to the Common Ancestor Dilemma Problem in Delegation-Based Object Systems". Proceedings of the 2004 Dynamic Aspects Workshop (103–119). http://www.cs.kuleuven.ac.be/~eddy/PUBLICATIONS/DAW2004.pdf.