Course contentsShow
← Java
Lesson 412 of 2,87010. Inheritance FundamentalsFree lesson

Field Initialization and Constructor Chaining Order

Understand when instance fields are initialized relative to superclass and subclass constructor execution.

Field Initialization and Constructor Chaining Order

What you'll learn: You'll understand the exact sequence in which fields are initialized and constructors execute when creating a subclass object.

The Complete Initialization Timeline

When you create an instance of a subclass, Java follows a precise, choreographed sequence. Understanding this order is crucial for avoiding bugs and writing predictable initialization code.

Here's what happens when you write new Dog():

1. Superclass fields are initialized (in declaration order)
2. Superclass constructor body executes
3. Subclass fields are initialized (in declaration order)
4. Subclass constructor body executes

Why This Order Matters

This sequence ensures that the superclass is fully constructed before the subclass adds its own state. The superclass knows nothing about subclass fields, so it must be completely ready first.

Think of it like building a house: you must finish the foundation (superclass) before adding the second floor (subclass). The foundation's concrete must set and its walls must be built before you can frame the upper level.

class Animal {
    String type = "Generic";  // 1. Initialized first
    
    Animal() {
        System.out.println("Animal constructor: " + type);  // 2. Runs second
    }
}

class Dog extends Animal {
    String breed = "Labrador";  // 3. Initialized third
    
    Dog() {
        // implicit super() happens before ANY of this
        System.out.println("Dog constructor: " + breed);  // 4. Runs last
    }
}

When you create new Dog(), the output is:

Animal constructor: Generic
Dog constructor: Labrador

Key Takeaway: Instance fields initialize from the top of the hierarchy down, immediately before each level's constructor body executes. Superclass completes fully before subclass initialization begins.