Java Initialization Order

Code

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
59
60
61
62
63
64
65
66
public class Main {
public static void main(String... args) {
new Out("Main start\n");
new Out("Before new a B object");
new Out();
new B();
new Out();
new Out("After new a B object");
new Out("");
new Out();
new Out(C.constCvar);
new Out();
new Out(C.staticCVar);
new Out();
new Out("Before new a C object");
new Out();
new C();
new Out();
new Out("After new a C object");
new Out("");
new Out("Main end");
}
}

class Out {
public Out() {
System.out.println("-------------------------");
}

public Out(String message) {
System.out.println(message);
}
}


class A {
public static Out o1 = new Out("A static member o1 initialize");
public Out o2 = new Out("A member o2 initialize");

{ new Out("A non-static block execute"); }

static { new Out("A static block execute"); }

public A() { new Out("A constructor execute"); }
}

class B extends A {
public static Out o3 = new Out("B static member o3 initialize");
public Out o4 = new Out("B member o4 initialize");

{ new Out("B non-static block execute"); }

static { new Out("B static block execute"); }

public B() { new Out("B constructor execute"); }
}

class C {
public static final String constCvar = "const C member";
public static String staticCVar = "static C member";

static { new Out("C static block execute"); }

public C(){ new Out("C constructor execute"); }

}

Output

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
Main start

Before new a B object
-------------------------
A static member o1 initialize
A static block execute
B static member o3 initialize
B static block execute
A member o2 initialize
A non-static block execute
A constructor execute
B member o4 initialize
B non-static block execute
B constructor execute
-------------------------
After new a B object

-------------------------
const C member
-------------------------
C static block execute
static C member
-------------------------
Before new a C object
-------------------------
C constructor execute
-------------------------
After new a C object

Main end