Java 方法重写:如何使用 super 关键字调用父类方法
在 Java 中,我们可以使用 super 关键字来调用父类的方法或属性。在方法重写中,我们可以使用 super 来调用父类中已经被重写的方法。
以下是使用 super 调用父类方法的示例:
class Animal {
public void move() {
System.out.println('动物可以移动');
}
}
class Dog extends Animal {
public void move() {
super.move(); // 调用父类方法
System.out.println('狗可以跑和走');
}
}
public class TestDog {
public static void main(String args[]) {
Animal a = new Animal(); // Animal 对象
Animal b = new Dog(); // Dog 对象
a.move(); // 执行 Animal 类的方法
b.move(); // 执行 Dog 类的方法
}
}
输出结果为:
动物可以移动
动物可以移动
狗可以跑和走
在上述示例中,我们定义了两个类 Animal 和 Dog。Dog 继承自 Animal 并重写了 move() 方法。在 Dog 的 move() 方法中,我们使用 super.move() 调用了 Animal 类中已经被重写的 move() 方法。然后,我们在子类中添加了一些新的代码。
在 main() 方法中,我们创建了一个 Animal 对象 a 和一个 Dog 对象 b。当我们调用 a.move() 时,将执行 Animal 类中的 move() 方法。当我们调用 b.move() 时,将执行 Dog 类中的 move() 方法。在 Dog 类的 move() 方法中,super.move() 首先调用了 Animal 类中已经被重写的 move() 方法,然后输出了一些新的信息。
原文地址: https://www.cveoy.top/t/topic/nZKG 著作权归作者所有。请勿转载和采集!