在Java中,子类不能直接调用父类的构造方法。但是,当创建子类的对象时,父类的构造方法会在子类的构造方法之前自动执行。这是通过使用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(),编译器会自动插入一个无参数的super()调用。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。