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

Có thể chỉ override một phương thức khi implement interface Java?

Không thể. Khi implements một interface, class phải cung cấp implementation cho TẤT CẢ các abstract method của interface đó. Nếu bỏ qua bất kỳ method nào → compile error.

Ví dụ lỗi: Thiếu implement method

interface Sample {
    void demoMethod1();
    void demoMethod2();
    void demoMethod3();
}

public class InterfaceExample implements Sample {
    public void demoMethod1() { System.out.println("Method-1"); }
    public void demoMethod2() { System.out.println("Method-2"); }
    // Thiếu demoMethod3() -> Compile error
}
InterfaceExample.java:6: error: InterfaceExample is not abstract and does not override abstract method demoMethod3() in Sample

Giải pháp 1: Implement rỗng (empty body)

public class InterfaceExample implements Sample {
    public void demoMethod1() { System.out.println("Method-1"); }
    public void demoMethod2() {} // Implement rỗng
    public void demoMethod3() {} // Implement rỗng
}

Giải pháp 2: Dùng default method (Java 8+)

Interface có thể định nghĩa method có body với từ khóa default. Class implement không bắt buộc override default method.

interface Sample {
    void demoMethod1(); // Abstract - bắt buộc implement
    
    default void demoMethod2() { // Default - tùy chọn override
        System.out.println("Default method 2");
    }
    
    default void demoMethod3() {
        System.out.println("Default method 3");
    }
}

public class InterfaceExample implements Sample {
    public void demoMethod1() { System.out.println("Method-1"); }
    // Không cần viết demoMethod2, demoMethod3
}
Method-1
Default method 2
Default method 3

Giải pháp 3: Làm class thành abstract

public abstract class InterfaceExample implements Sample {
    public void demoMethod1() { System.out.println("Method-1"); }
    // Không implement demoMethod2, demoMethod3 -> OK vì class abstract
}

Tóm tắt: Phải implement tất cả abstract method. Có 3 cách tránh viết code cho method không cần: implement rỗng, dùng default method, hoặc làm class abstract.