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

ใช้ Private Method ใน Interface ได้ตั้งแต่ Java 9

ได้ ตั้งแต่ Java 9 สามารถใช้ private methods ใน Interface ได้แล้ว

ตัวอย่างโค้ด

interface MyInterface {
    public abstract void demo();
    
    public default void defaultMethod() {
        privateMethod();
        staticPrivateMethod();
        System.out.println("This is a default method of the interface");
    }
    
    public static void staticMethod() {
        staticPrivateMethod();
        System.out.println("This is a static method of the interface");
    }
    
    private void privateMethod() {
        System.out.println("This is a private method of the interface");
    }
    
    private static void staticPrivateMethod() {
        System.out.println("This is a static private method of the interface");
    }
}

public class InterfaceMethodsExample implements MyInterface {
    public void demo() {
        System.out.println("Implementation of the demo method");
    }
    
    public static void main(String[] args) {
        InterfaceMethodsExample obj = new InterfaceMethodsExample();
        obj.defaultMethod();
        obj.demo();
        MyInterface.staticMethod();
    }
}

ผลลัพธ์


This is a private method of the interface
This is a static private method of the interface
This is a default method of the interface
Implementation of the demo method
This is a static private method of the interface
This is a static method of the interface

ประโยชน์ของ Private Methods ใน Interface

  • ลดการซ้ำโค้ด (Code Reuse) ระหว่าง default methods และ static methods
  • ซ่อนรายละเอียดการทำงานภายใน (Encapsulation)
  • แยก Logic ที่ซ้ำกันออกมาเป็น private method ใช้ร่วมกันได้

ข้อจำกัด

  • Private method ไม่สามารถเป็น abstract ได้
  • Private static method เรียกได้เฉพาะใน interface เดียวกัน
  • Private instance method เรียกได้จาก default method ใน interface เดียวกัน