Java super 關鍵字
示例
使用 super
呼叫 Dog
(子類)的超類
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
關鍵字指代超類(父類)物件。
它用於呼叫超類方法,並訪問超類建構函式。
super
關鍵字最常見的用法是消除超類和子類之間具有相同名稱的方法的混淆。
要理解 super
關鍵字,您應該對 繼承 和 多型 有基本的瞭解。
相關頁面
在我們的 Java 繼承教程 中閱讀更多關於繼承(子類和超類)的資訊。
在我們的 Java 多型教程 中閱讀更多關於多型的資訊。