I was practicing for my Java exam when I've came across this example:
class A1 {
static {
System.out.println("A1S");
}
public static void main(String args[]) {
new A3();
}
}
class A2 {
static {
System.out.println("A2S");
}
public A2() {
System.out.println("A2");
}
static A3 as = new A3();
}
class A3 extends A2 {
static {
System.out.println("A3S");
}
public A3() {
System.out.println("A3");
}
}
class A4 extends A3 {
public A4() {
super();
System.out.println("A4");
}
}
I was expecting the following output:
A1S
A2S
A3S
A2
A3
A2
A3
But I've received this output:
A1S
A2S
A2
A3
A3S
A2
A3
Shouldn't the static block in A3 be executed before the constructor output? The JavaDoc says :
Initialization of a class consists of executing its static initializers and the initializers for static fields (class variables) declared in the class. A class or interface type T will be initialized immediately before the first occurrence of any one of the following:
T is a class and an instance of T is created.
T is a class and a static method declared by T is invoked.
A static field declared by T is assigned.
A static field declared by T is used and the field is not a constant variable (§4.12.4).
T is a top level class (§7.6), and an assert statement (§14.10) lexically nested within T (§8.1.3) is executed.
A reference to a static field (§8.3.1.1) causes initialization of only the class or interface that actually declares it, even though it might be referred to through the name of a subclass, a subinterface, or a class that implements an interface