Careeroza
Initialization Order
What Runs When
When you write new Child(), Java runs several pieces of code in a fixed order. Knowing this order helps you debug strange null values and is a common interview question.
- Static blocks and static field initializers (once per class, parent class first).
- Instance field initializers and instance initializer blocks
{ ... }. - The constructor body.
See the Order
Example
public class Main {
public static void main(String[] args) {
System.out.println("-- first object --");
new Demo();
System.out.println("-- second object --");
new Demo();
}
}
class Demo {
static int s = log("static field");
int x = log("instance field");
static {
log("static block");
}
{
log("instance block");
}
Demo() {
log("constructor");
}
static int log(String msg) {
System.out.println(msg);
return 0;
}
}Output
-- first object -- static field static block instance field instance block constructor -- second object -- instance field instance block constructor
Note: Static parts run only for the first object. Instance parts run for every object, and the constructor body always runs last.