在Java中,子类不能直接调用父类的构造函数。但是,当创建子类对象时,父类的构造函数会自动执行。这是通过使用super()关键字来实现的。super()关键字可以在子类的构造函数中调用父类的构造函数。请注意,super()必须是子类构造函数中的第一个语句。
以下是一个示例,说明如何在子类中使用super()调用父类的构造函数:
// 父类
class Parent {
String name;
// 父类构造函数
Parent(String name) {
this.name = name;
}
}
// 子类
class Child extends Parent {
int age;
// 子类构造函数
Child(String name, int age) {
super(name); // 调用父类构造函数
this.age = age;
}
}
public class Main {
public static void main(String[] args) {
Child child = new Child("John", 18);
System.out.println("Name: " + child.name);
System.out.println("Age: " + child.age);
}
}
在这个例子中,Child类继承了Parent类。当创建Child对象时,Parent类的构造函数会自动执行,因为我们在Child类的构造函数中使用了super(name)来调用它。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。