Search code examples
javainterfacejava-8default

Interaction between extended class and implemented interface


public class Main {

public static class ClassBase {

    public void test() {
        System.out.println("1");
    }

}

public static interface Interface {

    default void test() {
        System.out.println("2");
    }

}

public static class MyClass extends ClassBase implements Interface {

}

public static void main(String[] args) {
    new MyClass().test();
}

}

In this example, it will always print 1. To print 2, I must override test in MyClass and return Interface.super.test().

Is there a way of making the Interface::test method override the ClassBase::test method without manually overriding the method in MyClass ? (to print 2 in the example)


Solution

  • If any class in the hierarchy has a method with same signature, then default methods become irrelevant. A default method cannot override a method from java.lang.Object. The reasoning is very simple, it’s because Object is the base class for all the java classes. So even if we have Object class methods defined as default methods in interfaces, it will be useless because Object class method will always be used. That’s why to avoid confusion, we can’t have default methods that are overriding Object class methods.

    Conclusion: Default method cannot override Instance method.