Sub topic 11
Field and constructor initialization order
When you create an object, Java does not fill in all its fields at once. It follows an order. Knowing that order helps you understand field values and avoid using a field before it is ready.
This chapter assumes you know basic Java syntax, fields, methods, constructors, static, and inheritance. You should also know that a superclass is a parent class and a subclass is a class that extends it.
The working order
Initialization is the process of giving fields their starting values. When you create an object, Java first gives all its instance fields default values. An instance field is a field that belongs to each object.
Java then runs field initializers and constructors. A field initializer is a value or expression written with a field declaration, such as int count = 5;.
For a simple parent and child class, the order is:
- Give all the new object’s instance fields their default values.
- Run the parent’s instance field initializers and instance initializer blocks, in the order they appear.
- Run the parent’s constructor body.
- Run the child’s instance field initializers and instance initializer blocks, in the order they appear.
- Run the child’s constructor body.
An instance initializer block is a group of statements inside braces in a class, but outside any method or constructor. It runs for each new object.
If constructors use this(...) to delegate to other constructors, their bodies run as the calls return. You will see this in the example below.
This diagram leaves out class initialization, which can happen before the object is created.
Default values
Before instance field initializers run, Java gives every instance field a default value. The default depends on the field’s type.
| Field type | Default value |
|---|---|
| Integer types, such as `int` | `0` |
| Decimal types, such as `double` | `0.0` |
| `boolean` | `false` |
| `char` | `'\u0000'`, the zero character |
| Reference types, such as `String` | `null` |
A reference is a value that can refer to an object. null means the reference does not refer to an object.
These defaults apply to fields, including fields declared in the child class. They do not automatically apply to local variables, which are variables declared inside methods or constructors. You must give a local variable a value before you use it.
A field initializer can replace a default. For example, int count = 5; changes the field from 0 to 5 when that initializer runs.
Class initialization comes first
A static field belongs to a class rather than to each object. A static initializer block is a block marked with static. It runs during class initialization.
Before the first object of a class is created, Java initializes that class if it has not already been initialized. Other uses of a class can also cause initialization earlier. In the usual case, Java initializes the parent class before the child class.
Within each class, static field initializers and static initializer blocks run in the order they appear. Class initialization normally happens once for a class, while instance initialization happens for every new object.
Worked example
This program shows static blocks, instance field initializers, instance initializer blocks, and constructors working together.
Save it as InitializationDemo.java. You need a Java development kit, such as JDK 17, to compile and run it.
class Parent {
static {
System.out.println("Parent static block");
}
int parentNumber = show("Parent field", 10);
{
System.out.println("Parent instance block");
}
Parent() {
System.out.println("Parent constructor");
}
static int show(String message, int value) {
System.out.println(message);
return value;
}
}
class Child extends Parent {
static {
System.out.println("Child static block");
}
int first = show("Child first field", 1);
{
System.out.println("Child instance block: first = " + first);
}
int second = show("Child second field", 2);
Child() {
this(3);
System.out.println("Child no-argument constructor");
}
Child(int number) {
super();
System.out.println("Child int constructor: " + number);
}
}
public class InitializationDemo {
public static void main(String[] args) {
System.out.println("First object");
new Child();
System.out.println("Second object");
new Child(8);
}
}Run it with:
javac InitializationDemo.java
java InitializationDemoThe output is:
First object
Parent static block
Child static block
Parent field
Parent instance block
Parent constructor
Child first field
Child instance block: first = 1
Child second field
Child int constructor: 3
Child no-argument constructor
Second object
Parent field
Parent instance block
Parent constructor
Child first field
Child instance block: first = 1
Child second field
Child int constructor: 8Follow the first object
new Child() starts the first creation. The parent and child static blocks run first because those classes have not yet been initialized.
Next, Java gives the object’s fields their default values. At this point, parentNumber, first, and second are all 0.
The no-argument Child constructor calls this(3). Constructor delegation is when one constructor calls another constructor in the same class. Here, this(3) calls Child(int number) with the argument 3. An argument is a value passed to a constructor or method.
Child(int number) calls super(), which calls the parent’s no-argument constructor. Before the parent constructor body runs, the parent field initializer and instance block run.
After the parent constructor finishes, the child’s field initializers and instance block run. They run in written order. That is why the block can print first as 1 before the initializer for second runs.
Finally, the body of Child(int number) runs. Control returns to the no-argument constructor, and its remaining statement runs.
Follow the second object
new Child(8) calls Child(int number) directly. It still runs the parent and child instance initializers because this is a new object.
The static blocks do not print again. The classes were already initialized when the first object was created.
The no-argument constructor does not run for the second object. There was no call to it.
Constructor chains and instance initializers
A constructor chain is the series of constructor calls used to build an object. A constructor can call another constructor in its own class with this(...), or a parent constructor with super(...).
For code compatible with Java 17, either call must be the first statement in the constructor. If a constructor has neither call, Java inserts super() when a suitable parent constructor is available.
The instance initializers for a class run only once per object, even when that class has a chain of this(...) calls. In the example, the child field messages appear once for each object, not once for each child constructor.
If a constructor calls this(...), the called constructor finishes before the rest of the calling constructor body runs. A chain that calls itself in a circle does not compile.
A common trap: calling methods too early
During parent construction, child fields still have their default values. This matters if the parent constructor calls a method that the child overrides. An overridden method is a child class method that replaces an inherited method.
Save this separate program as EarlyCallDemo.java:
class ParentForDemo {
ParentForDemo() {
printLabel();
}
void printLabel() {
System.out.println("Parent label");
}
}
class ChildForDemo extends ParentForDemo {
String label = "ready";
@Override
void printLabel() {
System.out.println("Label: " + label);
}
}
public class EarlyCallDemo {
public static void main(String[] args) {
ChildForDemo child = new ChildForDemo();
child.printLabel();
}
}Run it with:
javac EarlyCallDemo.java
java EarlyCallDemoThe output is:
Label: null
Label: readyThe parent constructor calls printLabel(). Because the object is a ChildForDemo, Java calls the child’s overridden method. But the child’s field initializer has not run yet, so label is still null.
After the parent constructor finishes, label = "ready" runs. The later call from main therefore prints ready.
Printing null is safe, but using it as an object is not. For example, calling label.length() at that early point would cause a NullPointerException, an error caused by using null where an object is needed.
Avoid calling methods that a child can override from constructors or instance initializers. They may reach child fields before those fields are ready.
Check your understanding
Exercise
In one class, an instance field starts with a = 2. An instance block then changes it with a *= 3. A later field initializer sets b = a + 1. The constructor body finally runs a++. What are a and b after construction?
Show answer
Both are 7. The block changes a to 6, so the initializer sets b to 7. The constructor then changes a to 7.
Exercise
In the first worked example, why do the child’s instance field initializers run only once for new Child(), even though two child constructors are involved?
Show answer
Child() delegates to Child(int). The child’s instance initializers run once for the new object, before the body of Child(int), not once for each constructor in the chain.
Exercise
Why did the first call to printLabel() in EarlyCallDemo print null?
Show answer
The parent constructor called the child’s overridden method before the child’s field initializer ran. The label field still had its default reference value, null.