Monday, November 24, 2014

Why Java Does Not Support Multiple Inheritance

Why java does not support multiple inheritance? This question is asked very frequently from entry lever to middle level developers in the interview. You need to know the reason why java does not support multiple inheritance in order to answer this question in a satisfactory way. Java came in existence after C and C++ and from the experience of C/C++ it was quite evident that multiple inheritance creates more problem than solving them. At the root of this question is is the problem which is caused by multiple inheritance which is know as Diamond problem.

So, lets try to understand what Diamond problem is. Suppose there is a Class A which is the super class for class B and class C. Now there is another class called D which inherits both B and C. This inheritance hierarchy creates diamond like structure.


Now suppose there are two methods with the same name in Class B and Class C and as D inherits from both B and C it will have two versions of that method available to it. So when we create the object of D and try to call such method there will be an ambiguity to which version of the method to call (B's method or C's method). To overcome this situation C/C++ users virtual keyword. Java designers being aware of this problem decided not to support multiple inheritance and came up with the idea of multiple interface inheritance.

If you can tell the interviewer about this Diamond problem you will be able to impress them. However beware of  follow up questions related to interface. One such potential question could be suppose I have two interfaces - InterfaceA and InterfaceB both having a varible called DUPLICATE_VALUE. Now further suppose that a class ClassXYZ implements both the interfaces and we created the instance of ClassXYZ and try to access this DUPLICATE_VALUE through the its instance:-

package com.sanjiv.miscellaneous;

public class TestInheritacne implements InterfaceB, InterfaceA{

/**
* @param args
*/
public static void main(String[] args) {
TestInheritacne t = new TestInheritacne();

t.DUPLICATE_VALUE;

}

}

The above code will fail to compile due to the ambiguity. The solution to it is to call the DUPLICATE_VALUE variable with the interface name as the variables in an interface are all static and final and can be call be called directly-

InterfaceA.DUPLICATE_VALUE

or

InterfaceB.DUPLICATE_VALUE 

No comments:

Post a Comment