Sub topic 7
Follow Object Initialization Order
You have seen that a subclass constructor calls a superclass constructor with super(...). This chapter covers the order in which Java runs everything when you write new Dog(). That order explains some confusing bugs.
This chapter assumes you know Java fields, constructors, and how to compile and run a program. It also assumes you read the previous chapter on constructor chaining.
Why Order Matters
An object of a subclass is built in layers. The superclass layer comes first and the subclass layer comes on top. Java builds the layers from the bottom up.
Suppose Dog extends Animal. When you create a Dog, the Animal part must be ready before the Dog part starts. A Dog constructor may depend on things that Animal sets up. Java guarantees this by running superclass code first.
There are two separate kinds of initialization:
- Static initialization is setup for the class itself. It runs once, when the class is first used.
- Instance initialization is setup for one object. It runs every time you use
new.
The Tools of Initialization
Java gives you four places to put setup code.
- A static initializer block is a block written as
static { ... }. It runs once for the class. - A field initializer is a value written next to a field, like
int count = 5;. - An instance initializer block is a plain
{ ... }block in the class body. It runs for every new object. - A constructor body is the code between the braces of a constructor.
Field initializers and instance initializer blocks run in the order they appear in the source file. Java does not run them in a separate pass, so a block that appears earlier runs earlier.
The Rules
Here is the full order for the first new Dog() in a program.
- Java loads and initializes
Animal's static parts, thenDog's static parts. The superclass always comes first. - Java allocates memory for the new
Dog. Every field starts with a default value:0for numbers,falsefor booleans, andnullfor object references. - The
Dogconstructor starts. Its first action is the call tosuper(...). If you did not write one, Java addssuper()for you. - The
Animalconstructor starts. It first calls its own superclass constructor, which isObject. - Back in
Animal, Java runsAnimal's field initializers and instance blocks in source order. - Java runs the rest of the
Animalconstructor body. - Control returns to
Dog. Java runsDog's field initializers and instance blocks in source order. - Java runs the rest of the
Dogconstructor body.
The key point is step 5 and step 7. Field initializers run right after the super(...) call finishes and before the rest of the constructor body.
A Worked Example
The best way to learn the order is to watch it happen. This program prints a message from every place that can hold setup code.
class Log {
static String say(String message) {
System.out.println(message);
return message;
}
}
class Animal {
static { Log.say("Animal static block"); }
private String kind = Log.say("Animal field initializer");
{ Log.say("Animal instance block"); }
Animal() {
Log.say("Animal constructor body");
}
}
class Dog extends Animal {
static { Log.say("Dog static block"); }
private String breed = Log.say("Dog field initializer");
{ Log.say("Dog instance block"); }
Dog() {
super();
Log.say("Dog constructor body");
}
}
public class Main {
public static void main(String[] args) {
Log.say("main starts");
new Dog();
Log.say("creating a second Dog");
new Dog();
}
}The Log.say method prints a message and returns it. Returning the text lets us use it as a field initializer, which needs a value.
Running this program prints:
main starts
Animal static block
Dog static block
Animal field initializer
Animal instance block
Animal constructor body
Dog field initializer
Dog instance block
Dog constructor body
creating a second Dog
Animal field initializer
Animal instance block
Animal constructor body
Dog field initializer
Dog instance block
Dog constructor bodyLook at the output in two parts.
- The static blocks printed once, before the first
Dogwas built. The secondnew Dog()did not print them again. - The remaining lines repeat for each object. In each repetition, every
Animalline comes before everyDogline.
main starts prints first because the Animal and Dog classes are not needed until new Dog() runs. Java loads classes lazily, which means only when they are first used.
Summary Table
| Step | What runs | How often |
|---|---|---|
| Superclass static blocks and static fields | Setup of the superclass itself | Once per class |
| Subclass static blocks and static fields | Setup of the subclass itself | Once per class |
| Superclass field initializers and instance blocks | Setup of the superclass layer | Once per object |
| Superclass constructor body | Rest of the superclass setup | Once per object |
| Subclass field initializers and instance blocks | Setup of the subclass layer | Once per object |
| Subclass constructor body | Rest of the subclass setup | Once per object |
Default Values Come First
Step 2 in the rules is easy to forget. Before any of your code runs, Java sets every field to its default value. A field you have not yet initialized is not garbage. It holds 0, false, or null.
This matters because code can read a field before its initializer has run. Java allows it, and you see the default value.
A Common Trap: Calling an Overridable Method in a Constructor
Here is the most important bug that comes from initialization order. A superclass constructor runs before the subclass fields are initialized. If that constructor calls a method that the subclass overrides, the overriding method runs on a half-built object.
class Base {
Base() {
describe();
}
void describe() {
System.out.println("Base describe");
}
}
class Child extends Base {
private String label = "ready";
private int count = 5;
Child() {
super();
}
@Override
void describe() {
System.out.println("label=" + label + ", count=" + count);
}
}
public class Main {
public static void main(String[] args) {
Child child = new Child();
child.describe();
}
}The output is:
label=null, count=0
label=ready, count=5Follow the steps to see why.
new Child()allocates the object.labelisnullandcountis0.- The
Childconstructor callssuper(), which runs theBaseconstructor. - The
Baseconstructor callsdescribe(). Dynamic dispatch picks the version inChild, because the object is really aChild. Child'sdescribe()runs. TheChildfield initializers have not run yet, so it prints the default values.- Control returns to
Child. Nowlabelbecomes"ready"andcountbecomes5. - The second call,
child.describe(), happens after construction and shows the real values.
You can avoid the problem in three ways:
- Call only
private,static, orfinalmethods from a constructor. Subclasses cannot override these. - Keep constructors simple. Assign fields and do nothing else.
- Move extra setup into a separate method that the caller invokes after construction.
Initialization Order Within One Class
Inside a single class, the order is the order of the source text. Both of these snippets look alike but behave differently.
class Counter {
private int first = 10;
private int second = first + 5; // works: first is already 10
}If you put second before first and used first in the initializer, the compiler would reject a plain read of a field that is declared later. The compiler protects you here. The protection has gaps, though. A method call can still read a field before it is set, as the previous section showed.
Static Fields Follow the Same Idea
Static fields and static blocks run in source order too, and the superclass comes first. They run once, when the class is first initialized. A class is initialized when you first create an instance, call a static method, or read a non-constant static field.
class Config {
static int defaultSize = 10;
static {
System.out.println("Config loaded, size " + defaultSize);
}
}
public class Main {
public static void main(String[] args) {
System.out.println("before");
int size = Config.defaultSize;
System.out.println("after " + size);
}
}This prints before, then Config loaded, size 10, then after 10. The static block runs when main first touches Config.
Quick Checklist
When you need to predict the output of a program, work through these questions.
- Is this the first use of the class? If so, run the static parts, superclass first.
- Which constructor was called? Follow its
super(...)call all the way up toObject. - On the way back down, run each class's field initializers and instance blocks, then its constructor body.
- If any method is called early, remember that unset fields hold default values.
Exercises
Exercise
A class Vehicle has a constructor that prints "Vehicle". A class Car extends Vehicle has a field initializer that prints "Car field" and a constructor body that prints "Car body". The Car constructor has no explicit super() call. In what order are the three messages printed when you run new Car()?
Show answer
"Vehicle", then "Car field", then "Car body". Java inserts super() at the start of the Car constructor, so the Vehicle constructor runs first. Then the Car field initializers run, and then the rest of the Car constructor body.
Exercise
In the Base and Child example, Child has the field private int count = 5;. Why does the overridden describe() print count=0 when it is called from the Base constructor?
Show answer
The Base constructor runs before the Child field initializers. At that moment count still holds its default value, 0. The initializer that sets it to 5 runs only after the super() call returns.
Exercise
A program creates three Dog objects in a row. How many times does the Dog static block run, and how many times does the Animal constructor body run?
Show answer
The Dog static block runs once, because static initialization happens once per class. The Animal constructor body runs three times, once for each object created.