Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Có thể override default method trong Java không?

Interface trong Java tương tự class nhưng chỉ chứa abstract method và field final/static.

Từ Java 8, static method và default method được giới thiệu trong interface. Khác với abstract method, chúng có implementation mặc định. Nếu interface có default method, class implement KHÔNG bắt buộc override (cung cấp body). Tóm lại: có thể truy cập default method qua object của class implement.

Ví dụ

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();
    }
}

Đầu ra

display method of MyInterface

Override default method

Có thể override default method của interface từ class implement.

Ví dụ

interface MyInterface {
    public static int num = 100;
    public default void display() {
        System.out.println("display method of MyInterface");
    }
}

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();
    }
}

Đầu ra

display method of class