您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
在Java中,子类在创建对象时会自动调用其直接父类的构造函数。这是为了确保父类的成员变量被正确初始化。调用父类构造函数的过程是自动进行的,无需在子类构造函数中显式地使用super()
关键字。但是,如果你需要在子类构造函数中调用父类的其他构造函数,你可以使用super()
关键字。
以下是使用super()
调用父类构造函数的几种情况:
super()
关键字显式地调用父类的一个带参数的构造函数。class Parent {
Parent(String message) {
System.out.println("Parent constructor called with message: " + message);
}
}
class Child extends Parent {
Child() {
super("Hello from child"); // 显式调用父类的带参数构造函数
}
}
super()
关键字调用父类的任何一个构造函数。class Parent {
Parent() {
System.out.println("Parent default constructor called");
}
Parent(String message) {
System.out.println("Parent constructor called with message: " + message);
}
}
class Child extends Parent {
Child() {
super("Hello from child"); // 显式调用父类的带参数构造函数
}
}
super()
关键字,Java编译器会自动在子类构造函数的第一行插入一个无参数的super()
调用,以调用父类的默认构造函数。class Parent {
Parent() {
System.out.println("Parent default constructor called");
}
}
class Child extends Parent {
Child() {
// 编译器自动插入 super();
System.out.println("Child constructor called");
}
}
总之,在Java中,子类构造函数会自动调用父类的默认构造函数(如果没有显式地调用其他构造函数)。如果需要调用父类的其他构造函数,可以使用super()
关键字。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。