Lesson · Object Initialization & Memory
Initialization order: the exact sequence, once and for all
17 min readInitialization Order
Static before instance, parent before child, fields and blocks before constructor bodies. The order is fixed, it explains some of the strangest bugs in the language, and it fits in one diagram.
The output that looks impossible
Start with a program whose output refuses to match its source:
class Parent { Parent() { print(); } // calls an overridable method void print() { System.out.println("parent"); } } class Child extends Parent { int value = 42; // initialised AFTER the parent constructor @Override void print() { System.out.println("child sees value = " + value); } } new Child(); // prints: child sees value = 0
Predict before reading on. The class says 42; the call prints 0. The value was not lost, and the initialiser was not skipped: it simply had not run yet. The next two sections show the exact sequence that produces this.
Two phases, two frequencies
Everything about an object's birth belongs to one of two phases, and they run at different times:
| Phase | What runs, in order | Trigger | Frequency |
|---|---|---|---|
| Class initialization | Static fields and static blocks, source order, parent class first | First active use of the class | Once per JVM, per class |
| Instance initialization | Fields and blocks in source order, then the constructor body; each class completes before its subclass | Every new | Once per object |
Static work belongs to the class; instance work belongs to the object. One happens once, the other every time, and the trap from the opening lives at the boundary between them.
The answer, traced
Back to the opening program. For new Child(), the exact sequence is:
- Memory is zeroed: every field of the whole object, parent and child alike, starts at its default.
valueis 0 before any code runs. - The Child constructor begins with an implicit
super(), so Parent's constructor runs first. - Parent's constructor calls
print(). Dispatch respects the runtime type even during construction, so the Child override runs. - The override reads
valueand finds 0: Child's field initialisers have not run yet. That is the printed line. - Control returns to Child: the field initialiser
int value = 42finally runs, then the constructor body. - The object is complete, and
valueis 42 for every use after construction.
Construction runs top-down, and fields initialise late. A constructor body can trust state that belongs to its own class or above; subclass state is still at defaults while it runs.
new Child() · ten constructs, one order
Phase
not startedfully constructed: 0
Output
nothing printed yet
One call to new Child() runs ten constructs in a fixed order. The phase pill tracks where the JVM is, the output log fills in exactly as code executes: statics once, then the instance chain, parent always before child.
The full order, once and for all
For new Child() where Child extends Parent, nothing varies. This list is the specification in practice:
- Zeroing: all fields of the new object are cleared to defaults before any code runs.
- Parent statics, then child statics: static fields and static blocks in source order, once per JVM, at the first active use of the class.
- Parent instance fields and blocks: source order, on every new object.
- Parent constructor body: completes before any child field initialises.
- Child instance fields and blocks: source order.
- Child constructor body: last, on a fully built parent.
Deep hierarchies repeat the middle of this list once per class: fields and blocks, then the constructor body, top-down, every time.
The other hazards of construction
The overridable-method trap has two siblings that bite in the same window, the time before the constructor returns:
- `this` escaping early: registering
thiswith another object, or starting a thread that reads it, publishes a half-built instance. Finish construction first, publish afterwards. - A throwing static initializer: the class fails to initialise. The first use surfaces
ExceptionInInitializerError; every later attempt getsNoClassDefFoundErrorwith the original cause attached, because the JVM never retries. - Initialisers run in source order: two initialisers that depend on each other must be written in the order they must run; the compiler will not reorder them for you.
Construction is the only time an object is half-built; let nothing observe it. No dispatch to overrides, no sharing this, no side effects in statics.
Static initialization, used well
Class initialization is the right place for constants that need logic: parsing a configuration string, building an unmodifiable lookup table, registering a codec. It is a bad place for anything that depends on the world, because it runs at a time nobody scheduled: the first active use, possibly deep inside unrelated code.
The JVM guarantees the phase happens exactly once and is thread-safe: every thread blocks until the initialising thread finishes. That convenience is for constants, not workflows; an initialiser that starts threads, reads files, or calls back into other classes invites deadlocks and loading-order puzzles.
- Triggers initialization:
new, a static method call, a non-constant static field read, subclass initialization, reflection. - Does not trigger it: declaring a reference of the type, or reading a compile-time constant, which javac inlines into the caller.
Initialise constants, not workflows. Once per JVM is a feature for lookup tables and a trap for side effects.
The construction playbook
Reading any constructor in any codebase, in order:
- Find every static field and static block. They run once, in source order, at first active use, parent class first.
- For each new object: zeroing, then walk the hierarchy top-down, each class running its fields and blocks before its constructor body.
- Check the calls inside constructor bodies: anything overridable, and anything that publishes
this, runs against a partially built object. - Check static initialisers for side effects. They must be safe to run once, at an unscheduled moment, under a JVM lock.
Zero, statics, parent fields, parent constructor, child fields, child constructor. The sequence never varies, and knowing it turns most initialization mysteries into arithmetic.
Never call an overridable method from a constructor
The parent constructor runs before the child's fields exist, but dispatch does not care: the child's override runs anyway, observing default values it never expected. The bug presents as a null or zero in code that looks correct. Make the method final or private, move the call out of the constructor, or accept that subclasses will be built in a partially valid state.
Interview angles
Walk through the order for new Child() where Child extends Parent.+
Parent statics, child statics (once each, at class initialization), then per object: zeroing, parent fields and blocks in source order, parent constructor body, child fields and blocks, child constructor body.
The static half runs at the first active use of Child, not at JVM start, and never again. The instance half repeats on every new. The parent's entire instance chain completes before the first child field initialiser runs, which is why a parent constructor can never trust subclass state.
class Parent { Parent() { System.out.println("parent ctor"); } } class Child extends Parent { int value = 42; // runs AFTER the parent constructor Child() { System.out.println("child ctor"); } }
Common misconception: That declarations at the top of the child class run early. Fields and blocks run when their own class's turn arrives: after the parent chain, before the child constructor body.
Follow-up: Where does zeroing fit in that order?
When do static initializers run, exactly?+
At the first active use of the class: new, a static method call, a non-constant static field read, subclass initialization, or reflection. Once per class loader, under a JVM lock.
Loading a class and initialising it are different events: the loader may read the class file early, while initialization waits for the first active use. Compile-time constants are inlined by javac, so reading one never triggers the class that declared it, and merely declaring a reference of the type triggers nothing.
class Config { static final int TIMEOUT = 30; // constant: inlined static final Map<String, Integer> LIMITS = buildLimits(); // triggers init }
Common misconception: That statics run at JVM start, or when the class file is loaded. They run lazily, at the first active use, which is where startup-order puzzles come from.
Follow-up: What happens if that initialisation throws?
What happens when a static initializer throws?+
The class fails to initialise. The first use surfaces ExceptionInInitializerError; every later attempt gets NoClassDefFoundError with the original cause attached.
The JVM marks the class erroneous and never retries the initialisation, so the failure is permanent for the life of the class loader. That is why the two errors travel together in production logs, and why the fix belongs in the initialiser, never in catch blocks sprinkled at every call site.
class Broken { static int x = 1 / 0; // ExceptionInInitializerError on first use }
Common misconception: That wrapping the first call in a try block and retrying recovers the class. Initialisation is attempted once; recovery means fixing the code and restarting.
Follow-up: How would you make such an initialiser fail loudly but recoverably?
Why is calling an overridable method from a constructor dangerous?+
Dispatch respects the runtime type even during construction, so a subclass override runs before subclass fields are initialised and reads defaults.
The opening example is the pattern: the parent constructor calls print(), the child override runs, and value is still 0 while the source says 42. Private, static and final methods are safe because nothing can dispatch past them, and a static factory that builds first and calls the method afterwards is the other clean escape.
class Parent { Parent() { init(); } void init() { } } class Child extends Parent { int value = 42; @Override void init() { System.out.println(value); } // prints 0 }
Common misconception: That values written in the child class are 'there' from the beginning. Code order decides what a constructor observes, not the layout of the source.
Follow-up: What is the smallest change that makes the example safe?
Does this during construction matter beyond overrides?+
Yes. Handing this to another object before the constructor finishes publishes a half-built instance: the other object can observe defaults or call methods on incomplete state.
Registering listeners, launching threads that capture this, and storing this in a shared collection are the classic escapes. The rule is build first, publish last: finish construction, then register. Immutable objects sidestep the problem entirely, because an object that cannot change is safe the moment its constructor returns.
class Service { Service(Registry registry) { registry.add(this); // escapes before construction completes } }
Common misconception: That the risk only exists in multithreaded code. A single-threaded caller can still act on the half-built object before the constructor returns.
Follow-up: How would you restructure that class so this leaves only after construction?