Một interface không thể implement interface khác trong Java.
- Một interface trong Java về cơ bản là một loại class đặc biệt. Giống như class, interface chứa methods và variables. Khác với class, interfaces luôn hoàn toàn abstract.
- Interface được định nghĩa giống như class trừ từ khóa interface thay cho class, variables khai báo trong interface là static và final và methods định nghĩa trong interface là public abstract methods.
- Một interface có thể extend bất kỳ số lượng interface nào nhưng một interface không thể implement interface khác, vì nếu implement interface thì các methods của nó phải được định nghĩa và interface không bao giờ có định nghĩa của bất kỳ method nào.
- Nếu cố implement interface bằng interface khác, sẽ bị compile-time error trong Java.
Ví dụ
interface MainInterface {
void mainMethod();
}
interface SubInterface extends MainInterface {
// Nếu đặt implements keyword thay vì extends,
// compiler throws an error.
void subMethod();
}
class MainClass implements MainInterface {
public void mainMethod() {
System.out.println("Main Interface Method");
}
public void subMethod() {
System.out.println("Sub Interface Method");
}
}
public class Test {
public static void main(String args[]) {
MainClass main = new MainClass();
main.mainMethod();
main.subMethod();
}
}Kết quả
Main Interface Method Sub Interface Method