在Java中,super
關鍵字用于引用父類(超類)的一個屬性、方法或構造器。它允許子類直接訪問父類的成員,從而實現代碼的重用和擴展。super
的使用場景包括:
super
關鍵字。這通常在子類的構造函數中使用,以確保父類部分被正確初始化。class Parent {
Parent() {
System.out.println("Parent constructor called");
}
}
class Child extends Parent {
Child() {
super(); // 調用父類的構造函數
System.out.println("Child constructor called");
}
}
super
關鍵字調用父類的原始實現。class Animal {
void makeSound() {
System.out.println("The animal makes a sound");
}
}
class Dog extends Animal {
@Override
void makeSound() {
super.makeSound(); // 調用父類的makeSound方法
System.out.println("The dog barks");
}
}
super
關鍵字引用父類的屬性。class Vehicle {
String color = "red";
}
class Car extends Vehicle {
String color = "blue";
void displayColor() {
System.out.println("Car color: " + color);
System.out.println("Vehicle color: " + super.color);
}
}
在上述示例中,Car
類繼承了Vehicle
類,并重寫了makeSound
方法。在displayColor
方法中,使用super.color
來訪問父類Vehicle
的color
屬性。
使用super
關鍵字可以提高代碼的可讀性和可維護性,同時確保父類的實現被正確地繼承和擴展。在設計模式中,super
的使用通常與繼承和多態相關,是實現代碼復用和擴展性的重要手段。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。