在Java中,当子类的构造方法需要调用父类的构造方法时,可以使用super关键字。super关键字用于引用父类(或基类)的一个对象。在构造方法中使用super关键字可以确保父类的构造方法在子类构造方法执行之前被调用。这有助于正确地初始化继承自父类的成员变量。
以下是一个示例,展示了如何在子类的构造方法中调用父类的构造方法:
// 父类
class Parent {
int x;
// 父类构造方法
Parent() {
x = 10;
System.out.println("Parent constructor called");
}
}
// 子类
class Child extends Parent {
int y;
// 子类构造方法
Child() {
super(); // 调用父类构造方法
y = 20;
System.out.println("Child constructor called");
}
}
// 主类
public class Main {
public static void main(String[] args) {
Child child = new Child();
}
}
在这个示例中,Child类继承了Parent类,并在其构造方法中使用super()调用了Parent类的构造方法。当创建一个Child类的实例时,首先会调用Parent类的构造方法,然后再调用Child类的构造方法。输出结果如下:
Parent constructor called
Child constructor called