Saturday, December 20, 2014

Why multiple inheritance is not supported in java?

We all know that, multiple inheritance is not supported in java and same can be achieved by interface concept. But why multiple inheritance is not supported in java? and how same can be achieved by interface?
Before discussing about above said points, we remember one thing about Class and Interface

  1. In Class all the methods are concrete methods
  2. In Interface all the methods are by default abstract methods

Why multiple inheritance is not supported in java?

There are two classes A and B which are having a method with same name called methodTest. Class SubClass is extending both classes A and B, so absolutely compiler will throw an error. Suppose compiler is allowing to generate the byte code, then what will happen during an execution? Absolutely JVM will not knowing to which method needs to be executed either from Class A or from Class B. This problem is called "Diamond Problem".


     class A {
           public void methodTest() {
                System.out.println("Method from Class A");
           }
     }
     class B {
           public void methodTest() {
                System.out.println("Method from Class B");
           }
     }
     public class SubClass extends A,B {
           public static void main(String args[]) {
                SubClass obj = new SubClass();
                obj.methodTest(); // JVM will not knowing to which method needs to be executed either from Class A or from Class B
           }
     }

How multiple inheritance is achieved by interface?

In interface, all the methods are by default abstract methods which means only method declaration will be there, there is no implementation in interface. Whenever interface is implemented by a class, all methods which are declared in the interfaces should be implemented in the class.


     public interface A {
           public void methodTest();
     }

     public interface B {
           public void methodTest();
     }

     public class ImplementationClass implements A,B {
           public static void main(String args[]) {
                ImplementationClass obj = new ImplementationClass();
                obj.methodTest();
           }

           public void methodTest() {
                System.out.println("Method from ImplementationClass class");
           }
     }

In above example, interface A and B are having the same abstract method methodTest. ImplementationClass implements both the interfaces and methodTest method is implemented. So there is no conflict to calling the methodTest method, because we have only one implementation for methodTest method which is in ImplementationClass class.

No comments:

Post a Comment