Search code examples
javainheritanceinterfacejava-8abstract

Why does Java not allow multiple inheritance but does allow conforming to multiple interfaces with default implementations


I am not asking this -> Why is there no multiple inheritance in Java, but implementing multiple interfaces is allowed?

In Java, multiple inheritance isn't allowed, but, after Java 8, Interfaces can have default methods (can implement methods itself), just like abstract classes. Within this context, it multiple inheritance should also be allowed.

interface TestInterface 
{ 
    // abstract method 
    public void square(int a); 

    // default method 
    default void show() 
    { 
      System.out.println("Default Method Executed"); 
    } 
} 

Solution

  • Things are not so simple.
    If a class implements multiple interfaces that defines default methods with the same signature the compiler will force you to override this method for the class.

    For example with these two interfaces :

    public interface Foo {
        default void doThat() {
            // ...
        }
    }
    
    public interface Bar {    
        default void doThat() {
            // ...
        }       
    }
    

    It will not compile :

    public class FooBar implements Foo, Bar{
    }
    

    You should define/override the method to remove the ambiguity.
    You could for example delegate to the Bar implementation such as :

    public class FooBar implements Foo, Bar{    
        @Override
        public void doThat() {
            Bar.super.doThat();
        }    
    }
    

    or delegate to the Foo implementation such as : :

    public class FooBar implements Foo, Bar {
        @Override
        public void doThat() {
            Foo.super.doThat();
        }
    }
    

    or still define another behavior :

    public class FooBar implements Foo, Bar {
        @Override
        public void doThat() {
            // ... 
        }
    }
    

    That constraint shows that Java doesn't allow multiple inheritancy even for interface default methods.


    I think that we cannot apply the same logic for multiple inheritances because multiples issues could occur which the main are :

    • overriding/removing the ambiguity for a method in both inherited classes could introduce side effects and change the overall behavior of the inherited classes if they rely on this method internally. With default interfaces this risk is also around but it should be much less rare since default methods are not designed to introduce complex processings such as multiple internal invocations inside the class or to be stateful (indeed interfaces cannot host instance field).
    • how to inherit multiple fields ? And even if the language allowed it you would have exactly the same issue as this previously quoted : side effect in the behavior of the inherited class : a int foo field defined in a A and B class that you want to subclass doesn't have the same meaning and intention.