有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

不使用Java的双冒号运算符

只是在java中尝试一下,发现了以下问题

DefaultAndStaticMethodMain.java:8: error: not a statement
        implementation1::sendNotification;
        ^
1 error

以下是我的代码

父接口:

public interface ParentInterface {
    default void callForCompletion() {
        System.out.println("<<<< Notification sending completed. >>>>");
    }
}

子接口:

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,并与IntelliJ 2019.3和JDK 11一起工作。我检查了IntelliJ是否支持JDK 13

谢谢

更新 我不小心在那里留下了分号,把它去掉了,请再检查一遍


共 (1) 个答案

  1. # 1 楼答案

    你打算让implementation1::sendNotification;行做什么?从下面的implementation2.sendNotification();行判断,似乎您正在试图调用implementation1上的sendNotification,它是这样写的:

    implementation1.sendNotification();
    

    ::符号是一个method reference,并且(正如错误消息所说)它是一个标识符,而不是一个语句,因此不能单独作为一行。类似地,您不能将implementation1;(变量)或ChildInterface;(类标识符)写为语句

    由于将方法引用传递给^{}.forEach(SomeInterfaceToBeRenamed::sendNotification);行进行编译,依次调用每个sendNotification()方法