Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

วิธีเข้าถึง Member Variable ของ Derived Class ผ่าน Interface Object ใน Java

เมื่อใช้ Reference ของ Interface (หรือ Superclass) ชี้ไปที่ Object ของ Subclass จะเข้าถึงได้เฉพาะ Member ที่ ประกาศใน Interface/Superclass เท่านั้น หากต้องการเข้าถึง Member ของ Subclass ต้อง Cast (Type Casting)

ปัญหา: เข้าถึงไม่ได้โดยตรง

interface Sample {
    void demoMethod1();
}

public class InterfaceExample implements Sample {
    public void display() { // เมธอดของ Subclass เท่านั้น
        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: อยู่ใน Interface
        obj.display();     // Compile Error: ไม่ได้อยู่ใน Interface Sample
    }
}

Error

InterfaceExample.java:14: error: cannot find symbol
    obj.display();
    ^
  symbol:   method display()
  location: variable obj of type Sample

วิธีแก้: ใช้ Casting

public static void main(String args[]) {
    Sample obj = new InterfaceExample();
    obj.demoMethod1();                    // เรียกผ่าน Interface ได้
    ((InterfaceExample) obj).display();   // Cast แล้วจึงเรียกได้
}

ผลลัพธ์

This is demo method-1
This is a method of the sub class

หลักการสำคัญ

  • Reference Type กำหนดว่าสามารถเรียก Member ไหนได้ (Compile-time check)
  • Actual Object Type กำหนด Implementation ที่ทำงานจริง (Runtime polymorphism)
  • Casting บอก Compiler ว่า "เรารู้ว่าตัวนี้คือ Subclass จริงๆ" -> อนุญาตให้เรียก Member ของ Subclass

ข้อควรระวัง

  • Cast ผิด Class จะได้ ClassCastException Runtime
  • ควรตรวจสอบด้วย instanceof ก่อน Cast (Java 16+ ใช้ Pattern Matching: if (obj instanceof InterfaceExample ie) ie.display();)
  • Design ที่ดี: ควรใช้ Interface/Superclass Reference ให้มากที่สุด ลด Casting ให้น้อยที่สุด