Java9 接口私有方法
在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