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

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

Upcasting (Sub class → Super class)

ทำได้เสมอและปลอดภัย (Implicit casting) เพราะ Sub class "is-a" Super class

ขั้นตอน

  1. สร้าง Sub class object: Sub sub = new Sub();
  2. กำหนดให้ Super reference: Super sup = sub; (ไม่ต้อง cast)
  3. ผ่าน Super reference เรียกได้เฉพาะ member ของ Super 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) {
        Sample sample = new Sample("Krishna", 20, "IT", 1256);
        Person person = sample; // Upcast (implicit)
        person.displayPerson(); // OK
        // person.displayStudent(); // Compile Error!
    }
}

ผลลัพธ์

Person: Krishna, 20

สรุป

คุณสมบัติUpcasting (Sub→Super)Downcasting (Super→Sub)
Cast Operatorไม่ต้อง (Implicit)ต้อง (Explicit)
Safetyปลอดภัยเสมออันตราย (อาจ ClassCastException)
AccessSuper members เท่านั้นSuper + Sub members
ใช้เมื่อPolymorphism, Method parametersต้องการ Sub-specific behavior