在Java中,构造方法不能直接继承。每个类都有自己的构造方法。但是,子类可以通过super
关键字调用父类的构造方法。这样,父类的构造方法会在子类的构造方法中被执行,从而实现了类似继承的效果。
以下是一个示例:
class Parent {
public Parent() {
System.out.println("Parent constructor called");
}
}
class Child extends Parent {
public Child() {
super(); // 调用父类的构造方法
System.out.println("Child constructor called");
}
}
public class Main {
public static void main(String[] args) {
Child child = new Child();
// 输出:
// Parent constructor called
// Child constructor called
}
}
在这个例子中,Child
类继承了Parent
类,并通过super()
调用了Parent
类的构造方法。这样,当我们创建一个Child
对象时,Parent
和Child
的构造方法都会被调用。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读:java类的构造方法可以重载吗