- ตัวแปร super หมายถึงอินสแตนซ์ของคลาสพาเรนต์ทันที
- ตัวแปรพิเศษสามารถเรียกใช้เมธอดคลาสพาเรนต์ได้ทันที
- super() ทำหน้าที่เป็นตัวสร้างคลาสหลักทันที และควรเป็นบรรทัดแรกในตัวสร้างคลาสลูก
เมื่อเรียกใช้เมธอดที่ถูกแทนที่ในเวอร์ชันซูเปอร์คลาส ซูเปอร์คีย์เวิร์ดจะถูกใช้
ตัวอย่าง
class Animal {
public void move() {
System.out.println("Animals can move");
}
}
class Dog extends Animal {
public void move() {
super.move(); // invokes the super class method
System.out.println("Dogs can walk and run");
}
}
public class TestDog {
public static void main(String args[]) {
Animal b = new Dog(); // Animal reference but Dog object
b.move(); // runs the method in Dog class
}
} ผลลัพธ์
สิ่งนี้จะให้ผลลัพธ์ดังต่อไปนี้ -
Animals can move Dogs can walk and run