Java 9 中接口里是否能有 private 方法或 private 静态方法?


是的,我们可以在 Java 9 中定义接口中的私有方法私有静态方法。我们可以使用这些方法来去除代码冗余。私有方法仅在该接口内有用或可访问,我们不能从一个接口访问或继承私有方法到另一个接口或类。

语义

interface <interface-name> {
   private static void methodName() {
      // some statements
   }
   private void methodName() {
      // some statements
   }
}

示例

interface Java9Interface {
   public abstract void method1();
   public default void method2() {
      method4();
      method5();
      System.out.println("Inside default method");
   }
   public static void method3() {
      method5();    //  static method inside other static method
      System.out.println("Inside static method");
   }
   private void method4() {    // private method
      System.out.println("Inside private method");
   }
   private static void method5() {    // private static method
      System.out.println("Inside private static method");
   }
}
public class PrivateStaticMethodTest implements Java9Interface {
   @Override
   public void method1() {
       System.out.println("Inside abstract method");
   }
   public static void main(String args[]) {
      Java9Interface instance = new PrivateStaticMethodTest();
      instance.method1();
      instance.method2();
      Java9Interface.method3();
   }
}

输出

Inside abstract method
Inside private method
Inside private static method
Inside default method
Inside private static method
Inside static method

更新于:23-Mar-2020

3K+ 次浏览

启动你的职业生涯

通过完成课程获得认证

开始
广告
© . All rights reserved.