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

Quy tắc cho private methods trong Interface Java 9

Java 9 thêm tính năng private methods cho interface. Private methods được định nghĩa dùng modifier private. Có thể thêm cả private và private static methods trong interface từ Java 9 trở đi.

Quy tắc cho private methods trong interface:

  • Private method có body trong interface nghĩa là không thể khai báo như abstract method bình thường. Nếu thử khai báo private method không có body sẽ ném lỗi: "This method requires a body instead of a semicolon".
  • Không thể dùng cả modifier private và abstract cùng lúc trong interface.
  • Nếu muốn truy cập private method từ static method trong interface thì method đó phải khai báo là private static method vì không thể tham chiếu static đến phương thức non-static.
  • Private static method dùng từ ngữ cảnh non-static nghĩa là có thể gọi từ default method trong interface.

Cú pháp

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

Ví dụ

interface TestInterface {
    default void methodOne() {
        System.out.println("This is a Default method One...");
        printValues(); // calling a private method
    }
    default void methodTwo() {
        System.out.println("This is a Default method Two...");
        printValues(); // calling private method...
    }
    private void printValues() { // private method in an interface
        System.out.println("methodOne() called");
        System.out.println("methodTwo() called");
    }
}

public class PrivateMethodInterfaceTest implements TestInterface {
    public static void main(String[] args) {
        TestInterface instance = new PrivateMethodInterfaceTest();
        instance.methodOne();
        instance.methodTwo();
    }
}

Kết quả

This is a Default method One...
methodOne() called
methodTwo() called
This is a Default method Two...
methodOne() called
methodTwo() called