Java 中 super() 與 this() 的區別
以下列出了 Java 中 super() 方法與 this() 方法之間的顯著區別。
| super() | this() | |
|---|---|---|
| 定義 | super() - 指代直接父類的例項。 | this() - 指代當前類例項。 |
| 呼叫 | 可用於呼叫直接父類的成員方法。 | 可用於呼叫當前類的成員方法。 |
| 建構函式 | super() 用作直接父類的建構函式,並且應為子類建構函式中的第一行。 | this() 用作當前類的建構函式,並可在帶引數的建構函式中使用。 |
| 重寫 | 當呼叫某個被重寫方法的超類版本時,應使用 super 關鍵字。 | 當呼叫某個被重寫方法的當前版本時,應使用 this 關鍵字。 |
示例
class Animal {
String name;
Animal(String name) {
this.name = name;
}
public void move() {
System.out.println("Animals can move");
}
public void show() {
System.out.println(name);
}
}
class Dog extends Animal {
Dog() {
//Using this to call current class constructor
this("Test");
}
Dog(String name) {
//Using super to invoke parent constructor
super(name);
}
public void move() {
// invokes the super class method
super.move();
System.out.println("Dogs can walk and run");
}
}
public class Tester {
public static void main(String args[]) {
// Animal reference but Dog object
Animal b = new Dog("Tiger");
b.show();
// runs the method in Dog class
b.move();
}
}輸出
Tiger Animals can move Dogs can walk and run
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP