Trace object creation and constructors
35 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Creating an object runs code in a fixed order: static setup once per class, then, for every new, the parent part before the child part. Once you know this order, any "What is the output?" question about constructors becomes a simple walk-through.
Two phases: the class, then the object
Java sets things up at two levels. The class level runs once, the first time a class is used: static fields and static blocks (opens in a new tab). The object level runs for every new: field initializers, instance blocks and the constructor body.
Example 1 · Static once, instance every time
class Bus { static int buses; int seats = 40;
static { System.out.println("static block"); }
{ System.out.println("instance block, seats = " + seats); }
Bus() { buses++; System.out.println("constructor, bus " + buses); }}
public class BusDemo { public static void main(String[] args) { System.out.println("main starts"); new Bus(); new Bus(); }}main starts static block instance block, seats = 40 constructor, bus 1 instance block, seats = 40 constructor, bus 2
What this code does
- The static block runs once, when
Busis first used bynew Bus(), not when the program starts. - For each object, the field
seatsgets 40 and the instance block runs, then the constructor body.
new first gives the object memory with default values (0, false, null). Then the constructor fills it in, so by the time its first line runs, the object already exists.
A class whose parent is not ready yet gets its parent set up first, so static setup also runs parent before child.
The order for one new Child()
For new Child() with Child extends Parent, the parent part is always built before the child part, as in Constructor order in inheritance (opens in a new tab). Static setup comes first, but only the first time each class is used.
Example 2 · Parent and child: the full order
class Person { String role = note("Person field");
static { System.out.println("Person static"); }
Person() { System.out.println("Person constructor"); }
static String note(String msg) { System.out.println(msg); return msg; }}
class Student extends Person { String college = note("Student field");
static { System.out.println("Student static"); }
Student() { System.out.println("Student constructor"); }}
public class OrderDemo { public static void main(String[] args) { new Student(); System.out.println("---"); new Student(); }}Person static Student static Person field Person constructor Student field Student constructor --- Person field Person constructor Student field Student constructor
What this code does
note(...)prints a message so you can see the exact moment each field is set.- First
new: both static blocks (parent first), then the parent part, then the child part. - Second
new: no static output; the four object steps repeat in the same order.
Example 3 · Realistic: automatic PNR numbers
class Booking { static int nextPnr = 4001; final int pnr = nextPnr++; String name;
Booking(String name) { this.name = name; System.out.println("PNR " + pnr + " for " + name); }}
class TatkalBooking extends Booking { static int tatkalCount;
TatkalBooking(String name) { super(name + " (Tatkal)"); tatkalCount++; }}
public class PnrDemo { public static void main(String[] args) { new Booking("Aarav"); new TatkalBooking("Priya"); new Booking("Kavya"); System.out.println("Next PNR: " + Booking.nextPnr + ", tatkal: " + TatkalBooking.tatkalCount); }}PNR 4001 for Aarav PNR 4002 for Priya (Tatkal) PNR 4003 for Kavya Next PNR: 4004, tatkal: 1
What this code does
final int pnr = nextPnr++;runs before the constructor body, sopnris ready when the body prints it.++after the name gives the old value, then adds 1.- The tatkal booking goes through
super(...), so it uses the same shared counter: one number series for all bookings.
Within one class, field initializers like int seats = 40; and { } blocks run in the order they are written. A constructor body is never mixed in between: it always runs after them.
Order of execution
Six steps of new Child()
This is the first time either class is used. Tap the steps in the order they run.
Following this() and super() chains
A constructor starts with this(...), super(...), or nothing, and then Java adds super();. To trace, first go down the chain of this(...) calls until you reach the constructor that calls super.
Example 4 · A this() chain: initializers run once
class Vehicle { Vehicle() { System.out.println("Vehicle()"); }}
class Car extends Vehicle { String model; int year;
{ System.out.println("Car block"); }
Car() { this("Swift"); System.out.println("Car()"); }
Car(String model) { this(model, 2024); System.out.println("Car(String)"); }
Car(String model, int year) { super(); this.model = model; this.year = year; System.out.println("Car(String, int)"); }}
public class ChainDemo { public static void main(String[] args) { Car c = new Car(); System.out.println(c.model + " " + c.year); }}Vehicle() Car block Car(String, int) Car(String) Car() Swift 2024
What this code does
- Going down:
Car()→Car(String)→Car(String, int), which callssuper(). SoVehicle()prints first. - The instance block runs once, right after
super()returns. Then the bodies finish inside out: the last called prints first.
That constructor builds the parent part. Then this class's field initializers and instance blocks run once, not once per constructor in the chain. Then the bodies finish from the inside out: the last one called prints first.
The chain itself is taught in Call one constructor from another with this() (opens in a new tab).
Trace the code
Trace a this() chain
Variables
None yet.
Output
(nothing printed yet)Line 19new Phone() picks the constructor with no arguments, Phone().
The trap: calling an overridden method in a constructor
A parent constructor may call a method that the child overrides. Dispatch still runs the child's version, but the child's part is not built yet: its fields still hold 0 or null.
Example 5 · Trap: an overridden method called from the parent constructor
class Account { Account() { System.out.println("Opening: " + describe()); }
String describe() { return "Account"; }}
class Savings extends Account { String owner = "Diya"; int rate = 4;
Savings() { System.out.println("Ready: " + describe()); }
@Override String describe() { return owner + " at " + rate + "%"; }}
public class TrapDemo { public static void main(String[] args) { new Savings(); }}Opening: null at 0% Ready: Diya at 4%
What this code does
Account()runs first and callsdescribe(). The object is aSavings, so the child version runs.- At that moment
ownerandrateare not set yet (step 5 has not happened), so they shownulland0.
This is a favourite interview puzzle, and a real bug. Keep constructors simple: set fields, check values, and do not call methods that a child class can override.
Predict the output
Too early for the child
Read the code and pick what it prints.
Round 1 of 2
private, static or final cannot be overridden, so calling it from a constructor is safe.A routine for exam questions
Constructor output questions look long, but a fixed routine stops you from losing track. The same rules also explain the compile errors you get when a chain is written wrongly.
- Keep a "class ready?" list. Write the static output the first time a class is used, never again.
- For each
new, write the constructor chain on the side, then run it from the top parent down. - Mark when field initializers run: right after
super(...)returns, before the rest of the body. - Fields read before they are set show their default:
0,falseornull.
Fix the error
Constructor errors
Read the error, then pick the line that fixes it.
Round 1 of 2
A bus is a vehicle. Read the error and fix the constructor.
Error
Bus.java:9: error: constructor Vehicle in class Vehicle cannot be applied to given types;
Bus(String number, int seats) {
^
required: StringNext step
Check your understanding
12 quick questions