【问题标题】:Lambda does not override an interface method from a separate fileLambda 不会覆盖来自单独文件的接口方法
【发布时间】:2019-06-24 18:44:14
【问题描述】:
  1. 当功能接口位于 lambda 覆盖它的同一文件中时,它可以正常编译。
package test.test;
public class Base {
    public static void main(String[] args) {
        Interface1 a = n -> System.out.println(2*n);
    }
}
interface Interface1 { 
    void multiplyByTwo(int x); 
}
  1. 当功能接口在单独的文件中并且基类实现它时,编译失败并出现Base is not abstract and does not override abstract method multiplyByFour(int) in Interface3错误。
package test.test;
public class Base implements Interface3 {
    public static void main(String[] args) {
        Interface3 b = n -> System.out.println(4*n);
    }
}
package test.test;
public interface Interface3 { 
    void multiplyByFour(int x); 
}
  1. 这里有什么问题吗?第二种情况下为什么lambda不覆盖方法?

【问题讨论】:

  • 你不需要实现就可以使用
  • Base 类不需要实现该类中的 lambda 匹配的接口。

标签: java lambda interface


【解决方案1】:

你的第一个例子有:

public class Base {

没有实现Interface1

但是,您的第二个示例有:

public class Base implements Interface3 {

哪个实现了Interface3

不确定您要在这里做什么,但这是预期的行为:

接口

当一个类实现interface时,你必须在类中实现所有方法

例如:

public interface IFoo {
    void bar();
}

和类:

public class FooImpl implements IFoo {
    // must implement bar method in IFoo
    public void bar() {
        System.out.println("I did something");
    }

}

在 main 方法中有一个 lambda 并不构成实现接口方法。

修复?

删除implements Interface3即可,不需要在你的类中实现接口就可以使用了。

【讨论】:

    猜你喜欢
    • 2013-11-14
    • 2014-10-23
    • 2014-07-17
    • 1970-01-01
    • 1970-01-01
    • 2016-08-12
    • 1970-01-01
    • 2017-10-20
    • 2019-07-12
    相关资源
    最近更新 更多