Java 中 super() 和 this() 的区别
java programming java 8object oriented programming更新于 2024/11/29 12:22:00
以下是 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() { //使用 this 调用当前类构造函数 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 引用但 Dog 对象 Animal b = new Dog("Tiger"); b.show(); // 运行 Dog 类中的方法 b.move(); } }
输出
Tiger Animals can move Dogs can walk and run