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