當我在主方法中將接口實現為 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必須實際聲明其聲明正在實現的所有接口中缺少的方法的實現。
添加回答
舉報
0/150
提交
取消