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

当我在主方法中将接口实现为 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.5

The number is 356

true


慕森王
浏览 100回答 1
1回答

守着一只汪

您所做的就是在 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必须实际声明其声明正在实现的所有接口中缺少的方法的实现。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java