为什么我得到的是默认方法的值而不是覆盖的方法的值?

1 java lambda functional-interface

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());
    }
}
Run Code Online (Sandbox Code Playgroud)

执行结果将为0,虽然我期望的是1。我不明白为什么不返回重写方法的结果,而是返回默认方法的结果。

kni*_*ttl 5

该语句MyInterface a = () -> someMethod();或多或少相当于以下代码:

MyInterface a = new MyInterface() {
  @Override int anotherMethod() {
    return someMethod();
  }
};
Run Code Online (Sandbox Code Playgroud)

someMethod()在示例中的任何地方都没有被覆盖,因此使用默认实现。的默认实现return 0。所以调用a.anotherMethod()预计会返回0

Test#anotherMethod您的代码永远不会调用重写的内容。如果要执行此方法,则必须调用this.anotherMethod()(或分配MyInterface a = this;)。