Implement multiple inheritance using 'extends'

Topics: Language Specification
Oct 23, 2012 at 6:34 PM
Edited Oct 24, 2012 at 5:43 PM

Why does this throw an error by the compiler?

Of course, we have to "solve" the diamond problem, but what are the reasons against multiple inheritance?


Coordinator
Oct 24, 2012 at 4:36 PM

At the risk of getting a little language-geeky - inheritance is generally split into two kinds of inheritance: interface inheritance and implementation inheritance.  Interface inheritance is the inheritance that let subclasses follow the same interface as parent classes.  There's no problem allowing multiple inheritance for interfaces, in fact you  can do this now in TypeScript:

interface MyX {
	x: number;
}

interface MyY {
	y: number;
}

class MyClass implements MyX, MyY {
	x: number;
	y: number;
}

function f(xyz: MyClass) {
	return xyz.x + xyz.y;
}

Implementation inheritance is where you run into the diamond problem.

Oct 24, 2012 at 5:50 PM

Thanks for your response.

But that's not what I'm looking for. For example, I have a base class A and I want to extend it using a new class B. But the latter class should also inherit methods of another independent class C.

Class C is actually a class defining some functions for event handling (addEventListener, ...).

And are there any plans for implementing abstract classes and methods? They're of course not implementable in the compiled JavaScript but the compiler could still warn about using a class with abstract functions.

Oct 31, 2012 at 5:08 PM

When you want to re-use behaviour form multiple classes, you can use delegation rather than inheritance.

You can read a detailed comparison of these two styles here:

http://www.objectmentor.com/resources/articles/inheritanceVsDelegation.pdf

Nov 27, 2012 at 12:30 PM

Sometimes the best solution really is to emulate multiple inheritance (more verbosely) using interfaces, an attribute and many forwarding methods.

Multiple inheritance is very unpopular though, partly I think because there are so many opinionated people who speak ill of it, and partly because it can be confusing in certain/many cases.

Personally I'm a fan of Scala's traits mechanism as an alternative to multiple inheritance as it solves the diamond problem using a sensible and clearly defined mechanism. However I also feel that Scala traits have arbitrary restrictions purely because people are scared of having it "look like multiple inheritance" and thus offend aforementioned opinionated people.