在Java中,子类可以通过super
关键字来调用父类的构造方法。这通常在子类的构造方法中使用,以确保父类的初始化逻辑在子类对象创建时得到执行。以下是使用super
调用父类构造方法的几种情况:
super()
来调用它。这是默认的行为,即使你不显式地写出super()
,编译器也会自动插入。class Parent {
public Parent() {
System.out.println("Parent's no-argument constructor called");
}
}
class Child extends Parent {
public Child() {
super(); // 显式调用父类的无参构造方法
System.out.println("Child's constructor called");
}
}
super
关键字,并传递相应的参数。class Parent {
public Parent(String message) {
System.out.println("Parent's constructor with message: " + message);
}
}
class Child extends Parent {
public Child(String message) {
super(message); // 调用父类的带参数构造方法
System.out.println("Child's constructor called");
}
}
class Grandparent {
public Grandparent() {
System.out.println("Grandparent's constructor called");
}
}
class Parent extends Grandparent {
public Parent() {
super(); // 调用Grandparent的无参构造方法
System.out.println("Parent's constructor called");
}
}
class Child extends Parent {
public Child() {
super(); // 调用Parent的无参构造方法,间接调用Grandparent的无参构造方法
System.out.println("Child's constructor called");
}
}
请注意,super
关键字不仅用于调用构造方法,还可以用于访问父类的方法和字段。但是,当涉及到构造方法时,super
的使用是必须的,以确保对象的正确初始化。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。