Interface trong Java tương tự class nhưng chỉ chứa abstract method và field final/static.
- Là đặc tả (specification) prototype method. Khi cần hướng dẫn programmer hoặc tạo contract chỉ định method/field nên như thế nào → định nghĩa interface.
- Class muốn tuân theo spec → implement interface và cung cấp body cho TẤT CẢ abstract method.
- Nếu không implement hết abstract method → compile error.
Vấn đề: Thêm method mới vào interface?
Giả sử đang dùng interface, đã implement hết abstract method. Sau đó thêm method mới. Lúc này TẤT CẢ class dùng interface sẽ bị lỗi trừ khi implement method mới trong từng class.
Để giải quyết → Từ Java 8 giới thiệu default method.
Default Method
Còn gọi là defender method hoặc virtual extension method. Định nghĩa bằng từ khóa default:
default void display() {
System.out.println("This is a default method");
}
Viết default implementation cho method trong interface → không cần implement trong class đã dùng interface.
Ví dụ
interface sampleInterface {
public void demo();
default void display() {
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();
obj.display();
}
}
Đầu ra
This is the implementation of the demo method This is a default method