Instance Initializer Blocks
You'll learn about instance initializer blocks—special code blocks that run during object construction, useful for complex or shared initialization logic.
What Are Instance Initializer Blocks?
An instance initializer block is a block of code enclosed in curly braces { } that appears directly inside a class body (not inside any method or constructor). Unlike static blocks, these run every time you create a new object, right before the constructor body executes.
Think of it like a "pre-constructor setup crew"—it arrives before the main constructor starts, ensuring certain initialization tasks are always completed, no matter which constructor you call.
Syntax
public class Product {
private String id;
private int stock;
// Instance initializer block
{
System.out.println("Initializing product...");
stock = 0; // Set default stock
}
public Product(String id) {
this.id = id;
}
}
Every time you create a new Product("ABC123"), the block runs first (printing the message and setting stock to 0), then the constructor body assigns the id.
When to Use Them
Instance initializer blocks shine when:
- You have common initialization logic shared across multiple constructors
- The initialization is complex (multiple lines, calculations, or setup steps)
- You want to initialize anonymous inner classes (coming later in your studies)
They execute in the order: field initialization → instance initializer blocks → constructor body.
Execution Order Recap
- Fields are initialized to their default values
- Field initializers run (values at declaration)
- Instance initializer blocks run (top to bottom)
- Constructor body runs
Key Takeaway: Instance initializer blocks let you run shared setup code before any constructor, helping avoid duplication when multiple constructors need the same initialization logic.