Sub topic 7
Follow Object Initialization Order
When you create an object with new, Java sets it up in a fixed order. This order decides which code runs first. If you know it, you can avoid bugs where a field has an unexpected value.
The Parent Runs First
A subclass is a class that extends another class with the extends keyword. The class it extends is the superclass, or parent. A constructor is a special block of code that runs when an object is created.
When you create a subclass object, Java works in this order:
- The superclass constructor runs.
- The subclass fields get their starting values.
- The rest of the subclass constructor runs.
The first line of a subclass constructor calls the superclass constructor with super(). If you do not write this line, Java adds it for you.
A Simple Example
Here is a program that prints each step, so you can see the order.
class Animal {
Animal() {
System.out.println("1. Animal constructor");
}
}
class Dog extends Animal {
private String name = initName();
Dog() {
System.out.println("3. Dog constructor");
}
private String initName() {
System.out.println("2. Dog field starts");
return "Rex";
}
}
public class Main {
public static void main(String[] args) {
new Dog();
}
}The output is:
1. Animal constructor
2. Dog field starts
3. Dog constructorThe Animal constructor runs first. Then Dog's field name is set. Then the Dog constructor body runs.
A Trap: Calling an Overridden Method Too Early
A problem happens when a superclass constructor calls a method that the subclass overrides. Overriding means the subclass writes its own version of a method. The subclass version runs, but the subclass fields are not set yet.
class Animal {
Animal() {
System.out.println("Animal constructor");
describe();
}
void describe() {
System.out.println("Animal describe");
}
}
class Dog extends Animal {
private String name = "Rex";
@Override
void describe() {
System.out.println("Dog name is " + name);
}
}
public class Main {
public static void main(String[] args) {
new Dog();
}
}The output is:
Animal constructor
Dog name is nullThe describe() method in Dog runs before name gets the value "Rex". So name is still null, which means "no value yet." A number field would show 0, and a true/false field would show false.
Exercise
Exercise
In the Animal and Dog classes above, Dog has the field private int age = 5; instead of the name field. Animal's constructor calls describe(), and Dog's describe() prints age. What does it print?
Show answer
It prints "Dog age is 0". The describe() method runs during the Animal constructor, before Dog's field gets its value of 5. An int field starts at 0 until its starting value is set.