在Java中,子类构造器中可以通过使用super()关键字来调用超类构造器。super()必须在子类构造器的第一行调用。这样可以确保超类的初始化代码在子类初始化之前执行。如果子类构造器没有显式地调用super(),编译器会自动插入一个无参数的super()调用。
以下是一个简单的例子:
class Parent {
Parent() {
System.out.println("Parent class constructor called");
}
}
class Child extends Parent {
Child() {
super(); // 调用超类构造器
System.out.println("Child class constructor called");
}
}
public class Main {
public static void main(String[] args) {
Child child = new Child();
}
}
输出结果:
Parent class constructor called
Child class constructor called
在这个例子中,当我们创建一个Child对象时,首先调用Parent类的构造器,然后调用Child类的构造器。通过使用super()关键字,我们可以显式地调用超类构造器。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。