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