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

Cách truy cập biến thành viên của lớp con (derived class) qua đối tượng interface trong Java

Khi dùng reference kiểu interface (hoặc lớp cha) trỏ đến object lớp con, bạn chỉ truy cập được các member khai báo trong interface/lớp cha. Muốn truy cập member riêng của lớp con, phải ép kiểu (cast).

Ví dụ lỗi: Không ép kiểu

interface Sample {
    void demoMethod1();
}

public class InterfaceExample implements Sample {
    public void display() {
        System.out.println("This is a method of the sub class");
    }
    
    public void demoMethod1() {
        System.out.println("This is demo method-1");
    }
    
    public static void main(String args[]) {
        Sample obj = new InterfaceExample();
        obj.demoMethod1(); // OK: khai báo trong interface
        obj.display();     // Compile error: display() không có trong interface Sample
    }
}
InterfaceExample.java:14: error: cannot find symbol
    obj.display();
    ^
  symbol: method display()
  location: variable obj of type Sample

Đúng: Ép kiểu (casting)

public static void main(String args[]) {
    Sample obj = new InterfaceExample();
    obj.demoMethod1();
    ((InterfaceExample) obj).display(); // Cast để truy cập method của class con
}
This is demo method-1
This is a method of the sub class

Best practice: instanceof trước khi cast

if (obj instanceof InterfaceExample) {
    ((InterfaceExample) obj).display();
}

Lưu ý: Từ Java 16+, có Pattern Matching for instanceof gọn nhẹ hơn:

if (obj instanceof InterfaceExample ie) {
    ie.display(); // Biến ie đã được cast tự động
}

Điều này tương tự khi dùng lớp cha tham chiếu đến lớp con (polymorphism).