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

Tại sao cần private method trong interface Java 9?

Interface hỗ trợ default method từ Java 8. Khi nhiều default method chia sẻ code chung, có thể viết default method khác để reuse. Nhưng: default method là public → tất cả class implement đều thấy và gọi được → rò rỉ logic nội bộ (confidential code).

Java 9 thêm private method trong interface: chỉ visible trong interface đó, không kế thừa, không truy cập từ class implement hoặc interface extends. Giải pháp cho confidential shared code.

Cú pháp

private void methodName() {
    // statements
}

Ví dụ

interface Operation {
    default void addition() {
        System.out.println("default method addition");
    }
    
    default void multiply() {
        division(); // gọi private method
        System.out.println("default method multiply");
    }
    
    private void division() { // private method
        System.out.println("private method division");
    }
}

class PrivateMethodTest implements Operation {
    public static void main(String args[]) {
        PrivateMethodTest test = new PrivateMethodTest();
        test.multiply();
    }
}

Kết quả

private method division
default method multiply

Private static method

Java 9 cũng hỗ trợ private static void method() – dùng cho shared logic trong static method / default method.

So sánh

Loại methodVisibilityInherited?Dùng cho
defaultpublicCó (có thể override)API extension, backward compat
private (instance)private trong interfaceKhôngShared logic cho default method
private staticprivate trong interfaceKhôngShared logic cho static/default method
staticpublicKhông (nhưng accessible via InterfaceName.method())Utility, factory

Lợi ích

  • Encapsulation: Ẩn implementation detail.
  • DRY: Don't Repeat Yourself – chia sẻ code an toàn.
  • Security: Logic nhạy cảm không lộ ra implementor.
  • Maintainability: Thay đổi private method không break implementor.

Private method trong interface hoàn thiện default method – cho phép reuse code mà không 희생 encapsulation.