Why do I get the value of the default method and not the overridden one?

76 Views Asked by At
interface MyInterface {
    default int someMethod() {
        return 0;
    }

    int anotherMethod();
}

class Test implements MyInterface {
    public static void main(String[] args) {
        Test q = new Test();
        q.run();
    }

    @Override
    public int anotherMethod() {
        return 1;
    }
    
    void run() {
        MyInterface a = () -> someMethod();
        System.out.println(a.anotherMethod());
    }
}

The execution result will be 0, although I expected 1. I don't understand why the result of the overridden method is not returned, but the result of the default method is returned.

3

There are 3 best solutions below

0
Kamil Krzywański On BEST ANSWER

Becouse you used another implementation with lambda, where implementation of another method is "some method". You can create interfaces with lambda. On this case you do

MyInterface a = new Test(); System.out.println(a.anotherMethod());

or :

    MyInterface a = () -> 1;
    System.out.println(a.anotherMethod());
0
knittl On

The statement MyInterface a = () -> someMethod(); is more or less equivalent to the following code:

MyInterface a = new MyInterface() {
  @Override int anotherMethod() {
    return someMethod();
  }
};

someMethod() is not overridden anywhere in your example, so the default implementation is used. The default implementation of return 0. So calling a.anotherMethod() is expected to return 0.

The overridden Test#anotherMethod is never called by your code. If you want to execute this method, you must call this.anotherMethod() (or assign MyInterface a = this;).

0
WJS On

Because you didn't call the overridden method.

MyInterface a = () -> someMethod();
System.out.println(a.anotherMethod());

a has nothing to do with the Test instance in which it is called.