Thursday, July 24, 2014

Multiple Inheritance in Interfaces supports in Java.

We all know that Java won't support multiple inheritance to avoid diamond problem. So there is no way of extending multiple classes in java. That ends the discussion about multiple inheritance in classes. But still Java allows multiple inheritance in Interfaces. That raises the question about the same diamond problem in Interface as well right? consider the below case where one interface extending multiple Interfaces.
   interface TestInter extends InterfaceA, InterfaceB {
       // methods of all extended interface.  
   } 
The above code have no errors or problems and works fine. But what we are trying to question is what happens if any of the interfaces having same method?? For example, first interface have a method test()
  interface InterfaceA {
     testMethod();
 }
And also the second interface have a method with same name
  interface InterfaceB {
     testMethod();
 } 
And now the interface TestInter extending these interfaces which having same method names. Java won't complain about that and it runs fine.. Again the question raises like, what happens if a class implement that TestInter?. Normally that class needs to implement all the methods inside the interface implemented and the methods of that extended interface(s). Having two interfaces same method, which method needs to implement and which interfaces method calls when calling a method on TestInter instance ??? The answer is that JVM is smart enough to know about this and it manages it. Let see what happens for that method with same name.
   interface InterfaceA {
      void testMethod();
  }
  interface InterfaceB {
      void testMethod();
  }
  interface TestInter extends InterfaceA, InterfaceB {
      // methods of TestInter.  
  }
  class TestClass implements TestInter {@
      Override
      public void testMethod() {
          //you see here  
          //method from A and B  
          //only one method overridden.    
      }
  }
The above compiles successfully and we won't face any issues with it further as well. Yes, a single implementation works for the both methods. Single implementation belongs to the both interfaces. Hence there is no diamond problem. A test case would be as below to test that. 
    InterfaceA intera = new TestClass();
    intera.testMethod(); // the same implementation  
    InterfaceB interb = new TestClass();
    interb.testMethod(); //the same implementation
That is all to test and you can find yourself that the implementation works for both interfaces. So before concluding we must be very clear while talking about multiple inheritance term. When we say multiple inheritance not supporting in Java, we have to clearly mention that it won't support in Classes. An interface can extend multiple interfaces. A class can implement multiple interfaces. However, a class can only extend a single class.