您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
是的,在Java中,构造函数可以调用父类的构造器。在子类的构造函数中,可以使用super
关键字来调用父类的构造器。这样做的目的是确保父类也被正确地初始化,从而避免潜在的问题。
当子类构造函数被调用时,Java会自动调用父类的无参构造器(如果存在)。但是,如果你需要调用父类的其他构造器,你需要显式地使用super
关键字并传递相应的参数。
以下是一个示例:
class Parent {
Parent() {
System.out.println("Parent constructor called");
}
Parent(String message) {
System.out.println("Parent constructor with message called");
}
}
class Child extends Parent {
Child() {
super(); // 调用父类的无参构造器
System.out.println("Child constructor called");
}
Child(String message) {
super(message); // 调用父类的带参构造器
System.out.println("Child constructor with message called");
}
}
public class Main {
public static void main(String[] args) {
Child child1 = new Child();
Child child2 = new Child("Hello, World!");
}
}
输出:
Parent constructor called
Child constructor called
Parent constructor with message called
Child constructor with message called
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。