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

แปลงตัวแปร Super Class เป็น Sub Class Type ใน Java

Downcasting (Super class reference → Sub class type)

ทำได้ก็ต่อเมื่อ Super class reference ชี้ไปที่ Sub class object จริงๆ (Runtime type เป็น Sub class)

ขั้นตอน

  1. สร้าง Sub class object กำหนดให้ Super class reference: Super sup = new Sub();
  2. Cast: Sub sub = (Sub) sup;
  3. เรียก method ของ Sub class ได้

ตัวอย่าง

class Person {
    String name; int age;
    Person(String name, int age) { this.name = name; this.age = age; }
    void displayPerson() { System.out.println("Person: " + name + ", " + age); }
}

class Sample extends Person {
    String branch; int studentId;
    Sample(String name, int age, String branch, int id) {
        super(name, age); this.branch = branch; this.studentId = id;
    }
    void displayStudent() { System.out.println("Student: " + name + ", " + branch + ", " + studentId); }
}

public class Main {
    public static void main(String[] args) {
        Person person = new Sample("Krishna", 20, "IT", 1256);
        Sample obj = (Sample) person; // Downcast
        obj.displayPerson();
        obj.displayStudent();
    }
}

ผลลัพธ์

Person: Krishna, 20
Student: Krishna, IT, 1256

⚠️ คำเตือน

ถ้า Super reference ชี้ไปที่ Super object จริง (ไม่ใช่ Sub) การ cast จะโยน ClassCastException ตอน Runtime ควรตรวจสอบด้วย instanceof ก่อน:

if (person instanceof Sample) {
    Sample obj = (Sample) person;
    // safe
}