Java Constructor Execution Ordering

Understanding initialization order across class loading, inheritance, and instance instantiation.

📜 The Golden Rule Sequence

  1. Static Initializers & Fields
    Parent static blocks/fields execute first, followed by Child static blocks/fields (runs once per class load).
  2. Parent Instance Initializers & Fields
    Parent non-static blocks and variable initializations run sequentially top-to-bottom.
  3. Parent Constructor Body
    The body of the Parent constructor executes (via implicit or explicit super() call).
  4. Child Instance Initializers & Fields
    Child non-static blocks and variable initializations run sequentially top-to-bottom.
  5. Child Constructor Body
    The body of the Child constructor finally executes.

💻 Example Java Classes

class Parent {
    static { System.out.println("1. Parent Static Block"); }
    
    { System.out.println("3. Parent Instance Block"); }
    
    Parent() {
        System.out.println("4. Parent Constructor");
    }
}

class Child extends Parent {
    static { System.out.println("2. Child Static Block"); }
    
    { System.out.println("5. Child Instance Block"); }
    
    Child() {
        // implicit super();
        System.out.println("6. Child Constructor");
    }
}

⚙️ Step-by-Step Execution Simulator

Click Step Execution to simulate running new Child().

// Console output will appear here...
Key Takeaway: Constructors do not run in isolation. Before a child constructor runs its body, it invokes super() to fully construct the parent object first. Static elements only run once when the class is loaded into the JVM.