Friday, June 26, 2009

Multiple inheritance in Java

I have always missed true multiple inheritance in Java (like, in C++). For e.g., we are not able to define a class as follows in Java:

class X extends A, B, C {

}

Though, I do not see any inheritance use case which cannot be solved by the current Java facilities, but I would love to have this facility in Java. I think, the most latest Java version (1.7) doesn't have this feature.

One workaround I can see, for multiple inheritance, is to define a class like following:

class X {
A a;
B b;
C c;
}

i.e., we could create private class members inside X (whose functionality we want to use in class X).

Though this might serve purpose for some of the cases, but it's not true multiple inheritance! This I think, is actually aggregation pattern.

Of course, Java has multiple inheritance of interfaces. But that is inheritance of method signatures, and not of implementation.

I guess, keeping the number of base classes to one, Java is much simpler syntactically, and has a simpler compiler implementation. Though I agree, that having a simple syntax (as the current Java inheritance facilities) which is powerful enough, and can solve many use cases is better, than having a complex syntactical facility, which might serve even more uses cases, but could also lead to semantically difficult programs, which may be difficult to maintain and debug, as complexity of the problem domain increases.

1 comment:

Javin Paul said...

In my opinion more convincing reason for not supporting multiple inheritance is complexity involved in constructor chaining, casting etc rather than diamond problem

Javin
Why multiple inheritance is not supported in Java