java 子类如何调用父类的方法
子类调用父类方法的方式
在Java中,子类可以通过super关键字或直接调用(当方法未被重写时)来访问父类的方法。以下是具体实现方式:
使用super关键字调用父类方法
class Parent {
void display() {
System.out.println("Parent class method");
}
}
class Child extends Parent {
@Override
void display() {
super.display(); // 调用父类的display方法
System.out.println("Child class method");
}
}
super.display()会显式调用父类的display()方法,即使子类重写了该方法。

直接调用未被重写的父类方法
class Parent {
void print() {
System.out.println("Parent method");
}
}
class Child extends Parent {
void invokeParent() {
print(); // 直接调用继承的父类方法
}
}
当子类未重写父类方法时,可以直接通过方法名调用。

调用父类的构造方法
class Parent {
Parent(String msg) {
System.out.println(msg);
}
}
class Child extends Parent {
Child() {
super("Calling parent constructor"); // 调用父类构造方法
}
}
通过super()可在子类构造方法中调用父类构造方法,且必须位于子类构造方法的第一行。
注意事项
super不能用于静态方法,静态方法属于类而非实例。- 如果父类方法被
private修饰,子类无法直接调用。 - 多层继承中,
super只能指向直接父类,不能跨级调用祖父类的方法。






