Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

กฎสำหรับ Private Methods ใน Interface ของ Java 9

Private Methods ใน Interface

Java 9 อนุญาตให้ interface มี private methods และ private static methods โดยใช้ modifier private

กฎสำคัญ

  • ต้องมี body: private method ต้องมี implementation ไม่ได้เป็น abstract method (error: "This method requires a body instead of a semicolon")
  • ห้ามรวม private และ abstract: ไม่ได้ใช้ modifier ทั้งคู่พร้อมกัน
  • Static context ต้องใช้ private static: ถ้า static method เรียก private method ต้องเป็น private static method
  • Private static method เรียกจาก non-static ได้: เรียกจาก default method ได้

Syntax

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

ตัวอย่าง

interface TestInterface {
    default void methodOne() {
        System.out.println("This is a Default method One...");
        printValues(); // เรียก private method
    }
    default void methodTwo() {
        System.out.println("This is a Default method Two...");
        printValues();
    }
    private void printValues() { // private method ใน 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();
    }
}

Output

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

สรุป

Private methods ใน interface ช่วย share code ระหว่าง default/static methods ได้อย่างปลอดภัย ต้องปฏิบัติกัดเกณฑ์ด้าน modifier และ body