Interaction between an extended class and an 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 have to override test

in MyClass

and return Interface.super.test()

.

Is there a way to make the method Interface::test

override the method ClassBase::test

without manually overriding the method in MyClass

? (for printing 2 in the example)

+3


source to share


1 answer


If any class in the hierarchy has a method with the same signature, the default methods become irrelevant. The default method cannot override the method from java.lang.Object. The rationale is very simple because Object is the base class for all java classes. Therefore, even if we have methods of the Object class defined as default methods in interfaces, it will be useless, since the method of the Object class will always be used. Therefore, to avoid confusion, we cannot use the default methods that override the methods of the Object class.



Conclusion: The default method cannot override an instance method.

+3


source







All Articles