以下是Java中super()和this()方法之间的显着区别。超()这个()定义super()-引用直接父类实例。this()-引用当前的类实例。
调用可用于调用直接父类方法。可以用来调用当前的类方法。
构造函数super()充当直接的父类构造函数,并且应该是子类构造函数的第一行。this()充当当前类的构造函数,并且可以在参数化的构造函数中使用。
覆写调用覆盖方法的超类版本时,将使用super关键字。调用覆盖方法的当前版本时,使用此关键字。
示例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() {
//用它来调用当前的类构造器
this("Test");
}
Dog(String name) {
//使用super调用父构造函数
super(name);
}
public void move() {
//调用超类方法
super.move();
System.out.println("Dogs can walk and run");
}
}
public class Tester {
public static void main(String args[]) {
//动物参考但狗对象
Animal b = new Dog("Tiger");
b.show();
//在Dog类中运行方法
b.move();
}
}
输出结果Tiger
Animals can move
Dogs can walk and run