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