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

คีย์เวิร์ด super ใน Java

  • ตัวแปร super อ้างอิงถึงอินสแตนซ์ของคลาสพาเรนต์โดยตรง
  • ตัวแปร super สามารถเรียกเมธอดของคลาสพาเรนต์โดยตรงได้
  • super() ทำหน้าที่เป็นคอนสตรัคเตอร์ของคลาสพาเรนต์โดยตรง และควรเป็นบรรทัดแรกในคอนสตรัคเตอร์ของคลาสลูก

เมื่อเรียกใช้เวอร์ชันของคลาสพาเรนต์ของเมธอดที่ถูก override คีย์เวิร์ด super จะถูกใช้

ตัวอย่าง

class Animal {    public void move() {       System.out.println("Animals can move");    } } class Dog extends Animal {    public void move() {       super.move(); // เรียกเมธอดของ super class       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