What is the order of constructor calls when you create an instance of a subclass, and why is it fixed?
The constructors run from the top of the chain down to the class you wrote. So the grandparent constructor runs first, then the parent, and then the child.
public class Main {
public static void main(String[] args) {
new ElectricCar("model-3", 500);
}
}
And here is the chain of three classes.
public class Vehicle {
protected final String registration;
public Vehicle(String registration) {
this.registration = registration;
System.out.println("Vehicle ready");
}
}
public class Car extends Vehicle {
protected final int seats;
public Car(String registration, int seats) {
super(registration);
this.seats = seats;
System.out.println("Car ready");
}
}
public class ElectricCar extends Car {
private final int batteryKwh;
public ElectricCar(String registration, int batteryKwh) {
super(registration, 5);
this.batteryKwh = batteryKwh;
System.out.println("ElectricCar ready");
}
}
And the output is this.
the order the message
---------------- ---------------
1 Vehicle ready
2 Car ready
3 ElectricCar ready
And why is the order fixed? Two reasons. The first one is that the child needs the parent to be ready before it can use anything. The parent's fields have to be set before the child's constructor can read them or call a parent method.
The second one is the Java language rule that makes it work. The call to the parent constructor, whether you write it or Java writes it for you, has to be the first statement of the constructor. So there is no way to run any child code before the parent is built.
the step what happens
------------------------------ ---------------------------------------------
1. memory is set aside the object gets its space
2. fields get default values 0, false or null
3. the top constructor runs the grandparent
4. the next one runs the parent
5. the last one runs the class you wrote
And there is one thing that is worth knowing about, and it is a source of bugs. When the parent constructor calls a method that the child has overridden, the child's version runs, and it runs before the child's own fields are set. So the child method sees the default values. That is the classic bug of calling an overridable method from a constructor.
And there is a second detail worth knowing about. The parent constructor runs before the child's constructor, so the parent cannot see anything that the child has set. If a parent needs something from the child then the design is wrong, and you should pass it to the parent constructor instead.
So the rule to remember is this. The chain runs from the top down, and the child is always built last.
The last question in this topic is about a parent with no no-argument constructor.