Default Methods ใน Interface
ตั้งแต่ Java 8 Interface สามารถมี method ที่มี body (implementation) ได้ โดยใช้คีย์เวิร์ด default เรียกว่า Default Methods หรือ Defender Methods
การ Override Default Methods
ได้** - Class ที่ implements Interface สามารถ override default method ได้
ตัวอย่างที่ 1: ไม่ Override (ใช้ default ของ Interface)
interface MyInterface {
public static int num = 100;
public default void display() {
System.out.println("display method of MyInterface");
}
}
public class InterfaceExample implements MyInterface {
public static void main(String args[]) {
InterfaceExample obj = new InterfaceExample();
obj.display(); // เรียก default ของ Interface
}
}
display method of MyInterface
ตัวอย่างที่ 2: Override ใน Class
public class InterfaceExample implements MyInterface {
public void display() {
System.out.println("display method of class");
}
public static void main(String args[]) {
InterfaceExample obj = new InterfaceExample();
obj.display(); // เรียก overridden method
}
}
display method of class
สรุป
- Default Methods ให้ implementation เริ่มต้นใน Interface
- Class implements สามารถ override ได้ (เหมือน method ปกติ)
- หาก implements หลาย Interface ที่มี default method ชื่อซ้ำ → บังคับ override และระบุ
InterfaceName.super.method()