刚刚尝试java中的东西,发现以下问题。
DefaultAndStaticMethodMain.java:8: error: not a statement
implementation1::sendNotification;
^
1 error
以下是我的代码。
父界面:
public interface ParentInterface {
default void callForCompletion() {
System.out.println("<<<< Notification sending completed. >>>>");
}
}
子接口(interface):
public interface ChildInterface extends ParentInterface {
public abstract void sendNotification();
static String printNotificationSentMessage() {
return "Notification is sent successfully.";
}
}
实现1:
public class Implementation1 implements ChildInterface {
@Override
public void sendNotification() {
System.out.println("Implementation --- 1");
System.out.println("Sending notification via email >>>");
}
}
实现2:
public class Implementation2 implements ChildInterface {
@Override
public void sendNotification() {
System.out.println("Implementation ---- 2.");
System.out.println("Sending notification via SMS >>>");
}
}
主要方法:
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);
}
}
我不确定我做错了什么,我在本地计算机上安装了 JDK 13,并使用带有 JDK 11 的 IntelliJ 2019.3。我检查了 IntelliJ 支持 JDK 13
谢谢。
更新 我错误地在那里留了一个分号,把它去掉了,请再检查一下。
最佳答案
方法引用与方法调用不同。这是两个不同的事情。
方法调用是一个独立的表达式,或者更准确地说,是一个表达式语句。这意味着在您的情况下
implementation2.sendNotification()
可以正常工作,正如您所期望的那样。但是,方法引用,
is used to refer to the invocation of a method without actually performing the invocation
and 不是一个独立的表达式。它只能用在也可以使用 lambda 表达式的地方。作为独立表达式的方法引用无法编译,就像没有赋值的算术表达式一样(例如
3 + 17;
)。这是由 Java 语言规范 § 14.8 强制执行的。和 § 15.13 .
更多阅读内容:
关于java - 双冒号运算符不适用于 Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60352155/