只是在java中尝试了一些东西,发现了以下问题。
DefaultAndStaticMethodMain.java:8: error: not a statement
implementation1::sendNotification;
^
1 error
Run Code Online (Sandbox Code Playgroud)
以下是我的代码。
父接口:
public interface ParentInterface {
default void callForCompletion() {
System.out.println("<<<< Notification sending completed. >>>>");
}
}
Run Code Online (Sandbox Code Playgroud)
子界面:
public interface ChildInterface extends ParentInterface {
public abstract void sendNotification();
static String printNotificationSentMessage() {
return "Notification is sent successfully.";
}
}
Run Code Online (Sandbox Code Playgroud)
实施1:
public class Implementation1 implements ChildInterface {
@Override
public void sendNotification() {
System.out.println("Implementation --- 1");
System.out.println("Sending notification via email >>>");
}
}
Run Code Online (Sandbox Code Playgroud)
实施2:
public class Implementation2 implements ChildInterface {
@Override
public void sendNotification() {
System.out.println("Implementation ---- 2.");
System.out.println("Sending notification via SMS >>>");
}
}
Run Code Online (Sandbox Code Playgroud)
主要方法:
public class DefaultAndStaticMethodMain {
public static void main(String[] args) {
Implementation1 implementation1 = new Implementation1();
implementation1::sendNotification; // Compilation error as shown above.
Implementation2 implementation2 = new Implementation2();
implementation2.sendNotification();
// Following works fine.
// Arrays.asList(implementation1, implementation2).stream().forEach(SomeInterfaceToBeRenamed::sendNotification);
}
}
Run Code Online (Sandbox Code Playgroud)
我不确定我做错了什么,我在本地机器上安装了 JDK 13 并使用带有 JDK 11 的 IntelliJ 2019.3。我检查了 IntelliJ 支持 JDK 13
谢谢。
更新 我错误地在那里留下了一个分号,将其删除,请再次检查。
你打算让这implementation1::sendNotification;条线做什么?经判断implementation2.sendNotification();线下,它看起来像你想叫sendNotification上implementation1,它是这样写的:
implementation1.sendNotification();
Run Code Online (Sandbox Code Playgroud)
该::符号是一个方法引用,并且(如错误消息所述)它是一个标识符,而不是一个语句,因此不能单独成为一行。同样,您不能将implementation1;(变量)或ChildInterface;(类标识符)写为语句。
该.forEach(SomeInterfaceToBeRenamed::sendNotification);行编译是因为您将方法引用传递给forEach(),并且它依次调用每个sendNotification()方法。