Java 继承:子类构造器如何影响父类构造器
以下是您提供的Java代码:
class Parent {
Parent() {
System.out.println('Parent constructor');
}
}
class Child extends Parent {
Child() {
super();
System.out.println('Child constructor');
}
}
public class Main {
public static void main(String[] args) {
Child child = new Child();
}
}
在这段代码中,Child类的构造器将会影响Parent类的构造器,因为在Child类的构造器中使用了super()来调用父类的构造器。
当创建Child类的对象时,首先会调用Parent类的构造器,然后再调用Child类的构造器。
在Parent类的构造器中,我们使用System.out.println('Parent constructor')语句来打印输出'Parent constructor'。
接下来,在Child类的构造器中,我们使用super()来调用父类的构造器,这样会执行Parent类的构造器。
因此,运行这段代码将会输出以下结果:
Parent constructor
Child constructor
首先,打印输出'Parent constructor',表示Parent类的构造器被调用。
然后,打印输出'Child constructor',表示Child类的构造器被调用。
因此,Child类的构造器会影响Parent类的构造器,通过super()调用来确保在Child类的构造过程中首先调用了父类的构造器。
原文地址: https://www.cveoy.top/t/topic/p4w 著作权归作者所有。请勿转载和采集!