Java程式中super()和this()的區別
除了各種其他關鍵字外,Java還提供this和super作為特殊關鍵字,它們主要分別用於表示類的當前例項及其超類。儘管兩者相似,但它們之間存在顯著差異,如下所示:
| 序號 | 關鍵字 | this | super |
|---|---|---|---|
| 1 | 表示和引用 | this關鍵字主要表示類的當前例項。 | 另一方面,super關鍵字表示父類的當前例項。 |
| 2 | 與類建構函式的互動 | this關鍵字用於呼叫相同類的預設建構函式。 | super關鍵字用於呼叫父類的預設建構函式。 |
| 3 | 方法訪問許可權 | 由於this關鍵字具有當前類的引用,因此它用於訪問當前類的方法。 | 可以使用super關鍵字訪問父類的方法。 |
| 4 | 靜態上下文 | this關鍵字可以從靜態上下文引用,即可以從靜態例項呼叫。例如,我們可以編寫System.out.println(this.x),這將列印x的值,而不會出現任何編譯或執行時錯誤。 | 另一方面,super關鍵字不能從靜態上下文引用,即不能從靜態例項呼叫。例如,我們不能編寫System.out.println(super.x),這將導致編譯時錯誤。 |
this與super的示例
Equals.jsp
class A {
public int x, y;
public A(int x, int y) {
this.x = x;
this.y = y;
}
}
class B extends A {
public int x, y;
public B() {
this(0, 0);
}
public B(int x, int y) {
super(x + 1, y + 1);// calls parent class constructor
this.x = x;
this.y = y;
}
public void print() {
System.out.println("Base class : {" + x + ", " + y + "}");
System.out.println("Super class : {" + super.x + ", " + super.y + "}");
}
}
class Point {
public static void main(String[] args) {
B obj = new B();
obj.print();
obj = new B(1, 2);
obj.print();
}
}輸出
Base class : {0, 0}
Super class : {1, 1}
Base class : {1, 2}
Super class : {2, 3}
廣告
資料結構
網路
關係資料庫管理系統(RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP