我们可以在 Java 9 中的接口中使用私有方法吗?
javaobject oriented programmingprogramming更新于 2025/9/6 2:52:17
是的,从 Java9 开始,您可以在接口中使用私有方法。
Example
interface MyInterface {
public abstract void demo();
public default void defaultMethod() {
privateMethod();
staticPrivateMethod();
System.out.println("This is a default method of the interface");
}
public static void staticMethod() {
staticPrivateMethod();
System.out.println("This is a static method of the interface");
}
private void privateMethod(){
System.out.println("This is a private method of the interface");
}
private static void staticPrivateMethod(){
System.out.println("This is a static private method of the interface");
}
}
public class InterfaceMethodsExample implements MyInterface {
public void demo() {
System.out.println("Implementation of the demo method");
}
public static void main(String[] args){
InterfaceMethodsExample obj = new InterfaceMethodsExample();
obj.defaultMethod();
obj.demo();
MyInterface.staticMethod();
}
}
Output
This is a private method of the interface This is a static private method of the interface This is a default method of the interface Implementation of the demo method This is a static private method of the interface This is a static method of the interface
相关文章
有用资源
java 参考教程 - 该教程包含有关 java 的更多信息:https://www.cainiaomax.com/java/

