What happens between writing new and having a usable object, and in what order do the constructors run in a hierarchy?
Between writing new and having an object you can use, four things happen in this order. The memory is set aside, the fields are given their default values, the constructors run from the parent down, and then the reference is handed back to your code.
public class Main {
public static void main(String[] args) {
Laptop laptop = new Laptop("pro", 16);
System.out.println(laptop.describe());
}
}
And here is the hierarchy that shows the order of the constructors.
public class Device {
protected final String kind;
public Device(String kind) {
this.kind = kind;
System.out.println("Device built");
}
}
public class Laptop extends Device {
private final int memoryGb;
public Laptop(String kind, int memoryGb) {
super(kind); // the parent constructor runs first
this.memoryGb = memoryGb;
System.out.println("Laptop built");
}
}
So the order in full is this.
the step what happens
--------------------------- --------------------------------------------
1. memory is allocated the runtime finds a block for the object
2. fields get defaults every field is set to the default for
its type, so 0, false or null
3. the parent constructor it runs first, and it can set the
runs fields that it owns
4. the child constructor it runs next, and it sets the fields
runs that the child owns
5. the reference is given your variable now points at the object
to you
And the reason the memory and the default values come first is worth knowing, because it explains a common surprise. The parent constructor runs after the fields have their defaults, so if the parent calls a method that the child has overridden, the method sees the child's fields with their default values and not the real ones. That is the classic problem with calling an overridable method from a constructor, and the rule is to keep the parent constructor to simple field assignments.
And there is one more thing about the order. When a class has several levels, the whole chain runs from the top down. So a class that extends a class that extends a class runs the constructors in the order of the tree, and the last one to run is the one you wrote.
So the rule to remember is this. Memory, then defaults, then the constructors from the parent down, and then your code gets the object.
The next two questions in this topic are about releasing resources and about the whole life of an object.