ปัญหา: เพิ่ม Method ใน Interface เดิม
Interface เป็นสัญญา (Contract) กำหนด abstract methods ที่ Class ต้อง implement หากเพิ่ม method ใหม่ใน Interface ทุก Class ที่ implements อยู่แล้วจะ compile error (ต้อง implement method ใหม่ทั้งหมด)
คำตอบ: Default Methods (Java 8+)
- เพิ่ม method พร้อม implementation ใน Interface ด้วย
default - Class ที่ implements อยู่แล้ว ไม่ต้องแก้ไข (Backward Compatibility)
- Class ใหม่สามารถ override ได้หากต้องการ
ตัวอย่าง
interface SampleInterface {
public void demo(); // abstract method
default void display() { // default method
System.out.println("This is a default method");
}
}
public class DefaultMethodExample implements SampleInterface {
public void demo() {
System.out.println("This is the implementation of the demo method");
}
public static void main(String args[]) {
DefaultMethodExample obj = new DefaultMethodExample();
obj.demo(); // ต้อง implement เอง
obj.display(); // ใช้ default ของ Interface
}
}
ผลลัพธ์
This is the implementation of the demo method This is a default method
ประโยชน์หลัก
- Backward Compatibility: เพิ่ม method ใน Interface ได้โดยไม่ทำลาย Class เก่า
- Code Reuse: ใส่ common logic ใน Interface ได้
- Multiple Inheritance of Behavior: Class ได้ behavior จากหลาย Interface