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

Why when I implement a lambda expression in the main method, the compiler doesn't say the interfaces are implemented?

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

你所做的就是在main方法中定义局部变量,其类型恰好与class 必须实施。

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

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 必须实际声明其声明正在实现的所有接口中缺失方法的实现。