Java对象初始化构造顺序

本文讨论JAVA中对象初始化时基类子类的static field,field ,static initial block,field initial block以及Constructor的调用顺序问题,通过如下实例来说明:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
public class MyTest {
public static void main(String[] args) {
Teacher teacher = new Teacher();
}
}
class Employee {
private static String staticField = staticField();
private String field = print();
public Employee() {
System.out.println("Employee constructor");
}
{
System.out.println("Employee block");
}
static {
System.out.println("Employee static block");
}
private static String staticField() {
System.out.println("Employee static field");
return "Employee staticField";
}
private String print() {
System.out.println("Employee field");
return "Employee field";
}
}
class Teacher extends Employee {
private static String staticField = staticField();
private String field = print();
public Teacher() {
System.out.println("Teacher constructor");
}
{
System.out.println("Teacher block");
}
static {
System.out.println("Teacher static block");
}
private static String staticField() {
System.out.println("Teacher static field");
return "Teacher staticField";
}
private String print() {
System.out.println("Teacher field");
return "Teacher field";
}
}

输出如下:

1
2
3
4
5
6
7
8
9
10
Employee static field
Employee static initial block
Teacher static field
Teacher static initial block
Employee field
Employee initial block
Employee constructor
Teacher field
Teacher initial block
Teacher constructor

上面的例子说明,在初始化类的对象的时候,构造器的调用顺序:

基类的 static field
基类的 static initial block
子类的 static field
子类的 static initial block
基类的 field
基类的 initial block
基类的 constructor
子类的 field
子类的 initial block
子类的 constructor

将上述声明顺序调换,初始化的顺序依旧不变