Complete Initialization Sequence: Fields, Blocks, Constructor
You'll learn the exact order Java follows when creating an object, ensuring you understand when each piece of initialization code runs.
The Full Picture
By now, you've learned about field initializers, instance initializer blocks, and constructors separately. But when you create an object with new, Java executes them in a specific, predictable order:
- Field initializers (in declaration order, top to bottom)
- Instance initializer blocks (in declaration order, top to bottom)
- Constructor body (the code inside the constructor you called)
Think of it like preparing a stage for a play: first you set up the basic props (fields), then you run through pre-show checks (blocks), and finally the director gives final instructions (constructor).
Example Walkthrough
public class Student {
private String name = "Unknown"; // Step 1: field initializer
private int age;
{
age = 18; // Step 2: instance block
System.out.println("Block executed");
}
private String id = generateId(); // Step 3: another field initializer
{
System.out.println("Second block"); // Step 4: second instance block
}
public Student(String name) {
this.name = name; // Step 5: constructor body
System.out.println("Constructor done");
}
private String generateId() {
System.out.println("Generating ID");
return "STU001";
}
}
When you call new Student("Alice"), the output is:
Generating ID
Block executed
Second block
Constructor done
Field initializers and blocks execute before any constructor code, allowing you to set up complex state step-by-step.
Key Takeaway: Object initialization follows a strict sequence: field initializers from top to bottom, then instance blocks from top to bottom, and finally the constructor body—guaranteeing consistent object setup every time.