Friday, January 10, 2014

Why Java/.Net does not support multiple Inheritance

The reasons for omitting multiple inheritance from the Java /.Net is  Simplicity of Language. To avoid complexity they have omitted the concept of Multiple Inheritance.

or instance, we can consider diamond problem of multiple inheritance.

We have two classes B and C inheriting from A. Assume that B and C are overriding an inherited method named ‘foo’ and they provide their own implementation. Now D inherits from both B and C doing multiple inheritance. D should inherit that overridden method, which overridden method will be used? Will it be from B or C? Here we have an ambiguity.
In C++ there is a possibility to get into this trap though it provides alternates to solve this. In java this can never occur as there is no multiple inheritance. Dynamic loading of classes makes the implementation of multiple inheritance difficult.

Multiple Inheritance is allowed for interfaces because the interface doesn’t implement the function. The function is always implemented by the class. So, in the above case, A,B and C will be interfaces, and D will implement foo. main knows which function to call because there's only one foo.

How C++ solve this problem?

class A                     { public: void eat(){ cout<<"A";} };
class B: virtual public A   { public: void eat(){ cout<<"B";} };
class C: virtual public A   { public: void eat(){ cout<<"C";} };
class D: public         B,C { public: void eat(){ cout<<"D";} };

int main(){
    A *a = new D();
    a->eat();
}

If we will not use virtual C++ compiler will give an error on compile time “Member is ambiguous:
…..”. After using virtual keyword it ensures that only one copy of super class(A) method will remain in Child class (D).

And Java/.Net  doesn’t support virtual keyword in inheritance chain.


No comments:

Followers

Link