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

问题描述 投票:0回答:2
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());
    }

}

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

java lambda functional-interface
2个回答
1
投票

语句

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

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

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

您的代码永远不会调用重写的

Test#anotherMethod
。如果你想执行这个方法,你必须调用
this.anotherMethod()


0
投票

因为您使用了 lambda 的另一个实现,其中另一个方法的实现是“某个方法”。您可以使用 lambda 创建接口。在这种情况下,你会做

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

或:

    MyInterface a = () -> 1;
    System.out.println(a.anotherMethod());
© www.soinside.com 2019 - 2024. All rights reserved.