在Java中,我们可以使用super
关键字来调用父类的方法。如果不确定父类是否重写了一个方法,可以通过super
关键字来安全地调用父类的版本。
下面是一个示例代码,展示了如何使用super
关键字来调用父类的方法:
class Parent {
public void method() {
System.out.println("Parent method");
}
}
class Child extends Parent {
@Override
public void method() {
System.out.println("Child method");
}
public void callParentMethod() {
super.method(); // 调用父类的方法
}
}
public class Main {
public static void main(String[] args) {
Child child = new Child();
child.method(); // 调用子类的方法
child.callParentMethod(); // 调用父类的方法
}
}
在上面的示例中,Parent
类定义了一个method
方法,Child
类继承Parent
类并重写了method
方法。在Child
类中,我们可以使用super.method()
语句来调用父类的方法。
在Main
类的main
方法中,我们创建了一个Child
对象并调用了method
方法。这将会调用子类的方法。然后,我们调用了Child
类的callParentMethod
方法,该方法内部使用super.method()
来调用父类的方法。
通过使用super
关键字,我们可以安全地调用父类的方法,而不需要知道父类是否重写了该方法。这样可以确保我们调用的是父类的版本。
上一篇:不知道附带查询的答案?
下一篇:不知道父元素如何检索子元素