【发布时间】:2015-11-20 14:01:45
【问题描述】:
class abc extends TestStart{
static{
System.out.println("c");
}
{
System.out.println("f");
}
public abc(){
System.out.println("d");
}
}
public class TestStart {
static {
System.out.println("A");
}
{
System.out.println("z");
}
public TestStart(){
System.out.println("b");
}
public static void main(String[] args) {
TestStart x = new abc();
TestStart y = new TestStart();
}
}
输出-----------> 一种 C z b F d z b
我认为这个的输出行为---->>>>> TestStart x = new abc(); --------应该是:-
- 将运行两个类的第一个静态块
- 然后由于 new abc() 将调用子类的 init 块。但是这里调用父类的 init
- 然后从 new abc() 调用 super(),从而调用父类构造函数。
- 在父类构造函数之前,会执行父类的init块。
- 然后parnet类的构造函数将执行
- 然后子类的构造函数将执行。
我应该得到以下输出: 一种 C F z b d z b
这种行为很大程度上源于父类和子类中没有init块。 请解释我提到的输出。
【问题讨论】:
-
"然后由于 new abc() 将调用子类的 init 块" 这听起来像是从屋顶开始建造房子......一个初始化的父实例是子类的基础,所以需要先构建。
标签: java inheritance constructor initialization instance