Java superคำสำคัญ
ตัวอย่าง
ใช้super
เรียก superclass ของDog
(subclass):
class Animal { // Superclass (parent)
public void animalSound() {
System.out.println("The animal makes a sound");
}
}
class Dog extends Animal { // Subclass (child)
public void animalSound() {
super.animalSound(); // Call the superclass method
System.out.println("The dog says: bow wow");
}
}
public class Main {
public static void main(String args[]) {
Animal myDog = new Dog(); // Create a Dog object
myDog.animalSound(); // Call the method on the Dog object
}
}
ความหมายและการใช้งาน
คีย์เวิร์ดอ้างถึงอ็อบเจ็กต์ ซูsuper
เปอร์คลาส (พาเรนต์)
มันถูกใช้เพื่อเรียกเมธอด superclass และเพื่อเข้าถึงตัวสร้าง superclass
การใช้super
คีย์เวิร์ดที่พบบ่อยที่สุดคือการขจัดความสับสนระหว่างซูเปอร์คลาสและคลาสย่อยที่มีเมธอดที่มีชื่อเดียวกัน
เพื่อให้เข้าใจsuper
คีย์เวิร์ด คุณควรมีความเข้าใจพื้นฐานเกี่ยวกับInheritanceและPolymorphism
หน้าที่เกี่ยวข้อง
อ่านเพิ่มเติมเกี่ยวกับการสืบทอด (subclasses และ superclasses) ในJava Inheritance Tutorialของเรา
อ่านเพิ่มเติมเกี่ยวกับ polymorphism ในJava Polymorphism Tutorialของเรา