📜  Java9 私有接口方法

📅  最后修改于: 2020-10-14 00:40:20             🧑  作者: Mango

Java 9专用接口方法

在Java 9中,我们可以在接口内创建私有方法。接口允许我们声明私有方法,这些方法有助于在非抽象方法之间共享通用代码。

在Java 9之前,在接口内创建私有方法会导致编译时错误。以下示例使用Java 8编译器进行编译,并引发编译时错误。

Java 9专用接口方法示例

interface Sayable{
default void say() {
saySomething();
}
// Private method inside interface
private void saySomething() {
System.out.println("Hello... I'm private method");
}
}
public class PrivateInterface implements Sayable {
public static void main(String[] args) {
Sayable s = new PrivateInterface();
s.say();
}
}

输出:

PrivateInterface.java:6: error: modifier private not allowed here

注意:要实现私有接口方法,请仅使用Java 9或更高版本来编译源代码。

现在,让我们使用Java 9执行以下代码。看到输出,它可以正常执行。

Java 9专用接口方法示例

interface Sayable{
default void say() {
saySomething();
}
// Private method inside interface
private void saySomething() {
System.out.println("Hello... I'm private method");
}
}
public class PrivateInterface implements Sayable {
public static void main(String[] args) {
Sayable s = new PrivateInterface();
s.say();
}
}

输出:

Hello... I'm private method

这样,我们也可以在接口内创建私有静态方法。请参见以下示例。

Java 9私有静态方法示例

interface Sayable{
default void say() {
saySomething(); // Calling private method
sayPolitely(); //  Calling private static method
}
// Private method inside interface
private void saySomething() {
System.out.println("Hello... I'm private method");
}
// Private static method inside interface
private static void sayPolitely() {
System.out.println("I'm private static method");
}
}
public class PrivateInterface implements Sayable {
public static void main(String[] args) {
Sayable s = new PrivateInterface();
s.say();
}
}

输出:

Hello... I'm private method
I'm private static method