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
廣告