Java 中的 super 關鍵字
Java 中的 super
關鍵字是一個引用變量,用於引用直接父類對象。每當您創建子類的實例時,父類的實例都會隱式創建,並由 super
引用變量引用。
Java super 關鍵字的用法
super
用於引用直接父類的實例變量。 我們可以使用 super
關鍵字訪問父類的數據成員或字段。如果父類和子類具有相同的字段,則使用它。
class Animal {
String color = "white";
}
class Dog extends Animal {
String color = "black";
void printColor() {
System.out.println(color); // 打印 Dog 类的颜色
System.out.println(super.color); // 打印 Animal 类的颜色
}
}
class TestSuper1 {
public static void main(String args[]) {
Dog d = new Dog();
d.printColor();
}
}
輸出:
black white
在上面的示例中,Animal 和 Dog 類都具有公共屬性 color。如果我們打印 color 屬性,它將默認打印當前類的顏色。要訪問父屬性,我們需要使用 super
關鍵字。
super
可用於調用父類方法。 super
關鍵字也可用於調用父類方法。如果子類包含與父類相同的方法,則應使用它。換句話說,如果方法被重寫,則使用它。
class Animal {
void eat() {
System.out.println("eating...");
}
}
class Dog extends Animal {
void eat() {
System.out.println("eating bread...");
}
void bark() {
System.out.println("barking...");
}
void work() {
super.eat();
bark();
}
}
class TestSuper2 {
public static void main(String args[]) {
Dog d = new Dog();
d.work();
}
}
輸出:
eating... barking...
在上面的示例中,Animal 和 Dog 類都具有 eat() 方法,如果我們從 Dog 類調用 eat() 方法,它將默認調用 Dog 類的 eat() 方法,因為優先級賦予局部方法。要調用父類方法,我們需要使用 super
關鍵字。
super
用於調用父類構造函數。 super
關鍵字也可用於調用父類構造函數。讓我們來看一個簡單的例子:
class Animal {
Animal() {
System.out.println("animal is created");
}
}
class Dog extends Animal {
Dog() {
super();
System.out.println("dog is created");
}
}
class TestSuper3 {
public static void main(String args[]) {
Dog d = new Dog();
}
}
輸出:
animal is created dog is created
注意:如果構造函數中沒有super()
或this()
,編譯器會在每個類構造函數中自動添加super()
。 (待補充)
眾所周知,如果不存在構造函數,編譯器會自動提供默認構造函數。但是,它還會將 super()
作為第一條語句添加。 (待補充)
另一個 super
關鍵字的示例,其中 super()
由編譯器隱式提供。 (待補充)
class Animal {
Animal() {
System.out.println("animal is created");
}
}
class Dog extends Animal {
Dog() {
System.out.println("dog is created");
}
}
class TestSuper4 {
public static void main(String args[]) {
Dog d = new Dog();
}
}
輸出:
animal is created dog is created
super
示例:實際應用(待補充)
讓我們看看 super
關鍵字的實際應用。這裡,Emp 類繼承 Person 類,因此 Person 的所有屬性都將默認繼承到 Emp。為了初始化所有屬性,我們正在從子類使用父類構造函數。通過這種方式,我們正在重用父類構造函數。
class Person {
int id;
String name;
Person(int id, String name) {
this.id = id;
this.name = name;
}
}
class Emp extends Person {
float salary;
Emp(int id, String name, float salary) {
super(id, name); // 重用父类构造函数
this.salary = salary;
}
void display() {
System.out.println(id " " name " " salary);
}
}
class TestSuper5 {
public static void main(String[] args) {
Emp e1 = new Emp(1, "ankit", 45000f);
e1.display();
}
}
輸出:
1 ankit 45000
參考:https://www.javatpoint.com/super-keyword
This revised output maintains the original meaning while using different wording and sentence structures. The "TBD" sections are left as they were in the original, as they represent areas that require further explanation or completion, not necessarily paraphrase.
免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。
Copyright© 2022 湘ICP备2022001581号-3