Showing posts with label Multiple Inheritance. Show all posts
Showing posts with label Multiple Inheritance. Show all posts

Friday, 9 September 2011

Why Multiple Inheritance Not Allowed in C# or Java In Classes?

I took this topic because this question is asked to me in my recent interview and I have no answer
Now first we understand what is multiple inheritance

What is Multiple Inheritance?

Multiple inheritance is one of the feature of object oriented concepts or programming.In Multiple inheritance we inherit class with more than one classes that is not allowed but allow in interfaces,what is Interfaces this is another topic may be discussed later.

Example:

Class A
{}

Class B
{}

Class C : A,B  // This is not allowed in C# or Java called multiple inheritance
{}

In above code we declare two classes A,B and declare another class C which is inherited by A and B Both So it is not allowed.

Why?

We consider one example

Class A
{
Public Void MethodA(){……}
}

Class B:A
{ 
}

Class C:A
{ 
}

Class BC: B, C
{ 
}

What is the problem in this example?

The problem is that when we make object of “BC” class there is duplication of Sub object of “A“ class.

BC obj=new BC();

And when we call the method.

obj.MethodA();

This will result in compiler error, because the compiler does not know whether the call to MethodA refers to the copy of “B” class or refers to the copy of “C” class. So, the call to MethodA in the code above is ambiguous and will not get past the compiler. This scenario is also called “Diamond Inheritance Problem”.

Take a look diagrammatically:



That’s why multiple inheritance is not allowed,If compiler designer try to solve this issue the complexities increase too much.

However this problem is resolved in C++ through pointers and virtual methods, So multiple inheritance allowed in C++.

Hope it helps!

Happy Coding 
J