为了账号安全,请及时绑定邮箱和手机立即绑定

为什么当我在 main 方法中实现 lambda 表达式时,编译器不说接口已实现?

为什么当我在 main 方法中实现 lambda 表达式时,编译器不说接口已实现?

慕森王 2023-08-23 11:37:42
当我在主方法中将接口实现为 Lambda 表达式时,它不会被视为已实现。我知道我可以在 main 方法之外实现它,但是如果我必须在 main 方法之外实现它,我不明白为什么我应该使用 Lambda 表达式。public class Driver implements Interface1, Interface2, Interface3 {    public static void main(String[] args) {        //Implementing Interface1        double x;        Interface1 obj = () -> 5.5;        x = obj.foo();        System.out.println(x);        //Implementing Interface2        String str;        Interface2 obj2 = (a) -> String.format("The number is %d", a);        str = obj2.foo(356);        System.out.println(str);        //Implementing Interface3        boolean tF;        Interface3 obj3 = (i, s) -> i == Integer.parseInt(s);        tF = obj3.foo(30, "30");        System.out.print(tF);    }在这里,我在第 1 行收到一条错误消息,告诉我接口未实现。它仍然可以编译并工作,我只是不明白为什么会收到此消息。目前的输出是:5.5The number is 356true
查看完整描述

1 回答

?
守着一只汪

TA贡献1872条经验 获得超3个赞

您所做的就是在 main 方法中定义局部变量,其类型恰好与类必须实现的接口一致。


您必须在类中定义为该类的所有接口提供实现的方法。例如:


public class Driver implements Interface1, Interface2, Interface3 {

    public static void main(String[] args) {

        // all code in here is irrelevant to the class implementing Interface1, Interface2, Interface3

    }


    public void interface1Method() {

        // whatever

    }


    public void interface2Method() {

        // whatever

    }


    public void interface3Method() {

        // whatever

    }

}

请注意,您不能为此使用 lambda;Driver必须实际声明其声明正在实现的所有接口中缺少的方法的实现。


查看完整回答
反对 回复 2023-08-23
  • 1 回答
  • 0 关注
  • 96 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信