亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

為什么當我在 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條經驗 獲得超4個贊

您所做的就是在 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 關注
  • 186 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號