Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Có thể có private method / private static method trong interface Java 9?

Có. Java 9 cho phép private method và private static method trong interface. Mục đích: tái sử dụng code (code reuse) cho các default method / static method khác trong cùng interface, đồng thời ẩn logic nội bộ (encapsulation).

Cú pháp

interface <interface-name> {
    private static void staticMethod() { ... }
    private void instanceMethod() { ... }
}

Ví dụ đầy đủ

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 gọi private static method
        System.out.println("Inside static method");
    }
    
    private void method4() { // private instance 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();
    }
}

Kết quả

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

Quy tắc truy cập

  • Private method chỉ gọi được bên trong cùng interface.
  • Không kế thừa (inherit) được sang class implement hoặc interface extends.
  • Private static method gọi được từ static method và default method.
  • Private instance method chỉ gọi được từ default method (instance context).

Tại sao cần?

Trước Java 9: code chung phải đặt trong default method → public → class implement thấy được → rò rỉ logic nội bộ. Java 9: private method giữ logic bí mật, an toàn.