我有两个类Parent和Child
public class Parent {
public Parent() {
System.out.println("Parent Constructor");
}
static {
System.out.println("Parent static block");
}
{
System.out.println("Parent initialisation block");
}
}
public class Child extends Parent {
{
System.out.println("Child initialisation block");
}
static {
System.out.println("Child static block");
}
public Child() {
System.out.println("Child Constructor");
}
public static void main(String[] args) {
new Child();
}
}
上述代码的输出将为
Parent static block
Child static block
Parent initialization block
Parent Constructor
Child initialization block
Child Constructor
为什么Java要按这个顺序执行代码?决定执行顺序的规则是什么?
发布于 2016-01-26 04:08:24
我在视觉上学习,所以这里有一个顺序的可视化表示,作为一个SSCCE
public class Example {
static {
step(1);
}
public static int step_2 = step(2);
public int step_8 = step(8);
public Example(int unused) {
super();
step(10);
}
{
step(9);
}
// Just for demonstration purposes:
public static int step(int step) {
System.out.println("Step " + step);
return step;
}
}
public class ExampleSubclass extends Example {
{
step(11);
}
public static int step_3 = step(3);
public int step_12 = step(12);
static {
step(4);
}
public ExampleSubclass(int unused) {
super(step(7));
step(13);
}
public static void main(String[] args) {
step(5);
new ExampleSubclass(step(6));
step(14);
}
}
这将打印:
Step 1
Step 2
Step 3
Step 4
Step 5
Step 6
Step 7
Step 8
Step 9
Step 10
Step 11
Step 12
Step 13
Step 14
请记住,static
部件的顺序很重要;回顾一下Example
的static
内容和ExampleSubclass
的顺序之间的区别。
还要注意,无论顺序如何,实例初始化块总是在构造函数中的super()
调用之后立即执行(即使该调用是隐含的/省略的)。但是,在初始化块和字段初始化器之间,顺序确实很重要。
发布于 2013-10-24 16:59:40
有几条规则在起作用
super();
。初始化块甚至在构造函数调用之前就开始起作用了,所以这就是为什么首先调用它。现在你的父类被创建了,程序可以继续创建子类,这个子类将经历同样的过程。解释:
首先执行父级的
发布于 2013-10-24 17:09:45
首先只运行子类(注释extend子句)来查看简单的流。
第二个--去Static block vs. initializer block in Java?,阅读那里被接受的答案。
编辑:
静态,(非静态)初始化器和Constructor.
https://stackoverflow.com/questions/19561332
复制相似问题