Search code examples
javalambdafunctional-interface

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


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.


Solution

  • 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());