Upcasting (Sub class → Super class)
ทำได้เสมอและปลอดภัย (Implicit casting) เพราะ Sub class "is-a" Super class
ขั้นตอน
- สร้าง Sub class object:
Sub sub = new Sub(); - กำหนดให้ Super reference:
Super sup = sub;(ไม่ต้อง cast) - ผ่าน 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) |
| Access | Super members เท่านั้น | Super + Sub members |
| ใช้เมื่อ | Polymorphism, Method parameters | ต้องการ Sub-specific behavior |