Say a project contains several classes, each of which has a static initializer block. In what order do those blocks run? I know that within a class, such blocks are run in
There is one case in which a static block will not be called.
class Super {
public static int i=10;
}
class Sub extends Super {
static {
system.out.println("Static block called");
}
}
class Test {
public static void main (String [] args) {
system.out.println(Sub.i);
}
}
The above code outputs 10
Update from an "editor"
The technical explanation for this is in JLS 12.4.1
"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."
The intuitive explanation is Super.i and Sub.i are actually the same variable, and nothing in Sub actually needs to be initialized for the Super.i to get the correct value.
(It would be different if the initialization expression for Super.i referred to the Sub class. But then you would have a cycle in the initialization order. A careful reading of JLS 12.4.1 and JLS 12.4.2 explains that this is allowed, and allows you to work out exactly what would happen in practice.)