Call one constructor from another with this()
35 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)Your class has three constructors, and each one repeats the same set-up lines. Fix a bug in one and you must remember to fix the other two.
One constructor does the real work
Constructor chaining is calling one constructor from another constructor of the same class using this(...). The short constructors pass their values to one full constructor, so the set-up code is written only once.
Overloaded constructors repeat the same assignments and checks, and one copy can be forgotten. Pick one full constructor that sets every field and does every check; each of the others just calls it with this(...).
Example 1 · One constructor does the work
class Ticket { String passenger; String berth; int fare;
Ticket(String passenger) { this(passenger, "No preference", 650); }
Ticket(String passenger, String berth) { this(passenger, berth, 650); }
Ticket(String passenger, String berth, int fare) { if (fare < 0) { throw new IllegalArgumentException("Fare cannot be negative"); } this.passenger = passenger; this.berth = berth; this.fare = fare; }}
public class ChainDemo { public static void main(String[] args) { Ticket t1 = new Ticket("Priya"); Ticket t2 = new Ticket("Arjun", "Lower"); System.out.println(t1.passenger + ", " + t1.berth + ", Rs. " + t1.fare); System.out.println(t2.passenger + ", " + t2.berth + ", Rs. " + t2.fare); }}Priya, No preference, Rs. 650 Arjun, Lower, Rs. 650
What this code does
- The two short constructors fill in default values and pass everything to the full one with
this(...). - The assignments and the fare check are written once, so they apply to every ticket.
A rule now lives in exactly one place. Change the check once, and every way of creating a Ticket follows it.
How this(...) works
this(...), with brackets, is a call to another constructor of the same class on the same object. It is allowed only as the first statement of a constructor.
this(...) with brackets is a constructor call, not the field access this.name. It runs another constructor of the same class on the same object, so no second object is made.
Example 2 · A chain of three constructors
class Student { String name; int marks;
Student() { this("New student"); System.out.println("3. Student() finishes"); }
Student(String name) { this(name, 0); System.out.println("2. Student(String) finishes"); }
Student(String name, int marks) { this.name = name; this.marks = marks; System.out.println("1. Full constructor sets " + name); }}
public class TraceDemo { public static void main(String[] args) { Student s = new Student(); System.out.println(s.name + " " + s.marks); }}1. Full constructor sets New student 2. Student(String) finishes 3. Student() finishes New student 0
What this code does
new Student()entersStudent(), which jumps toStudent(String), which jumps to the full constructor.- The full constructor finishes first; then each caller runs the lines after its
this(...), in reverse order. - Only one object exists the whole time; three constructors worked on it.
Java picks which constructor to call from the arguments, exactly as with new. Chains can be longer than one step: each link moves one step closer to the full constructor.
this() must be the first statement
In Java 17, this(...) must be the very first statement of the constructor; even a println above it is an error. So a constructor has at most one this(...), and an ordinary method has none.
Example 3 · A line above this(): the Java 17 error
class Ticket { String name; int seat;
Ticket(String name) { System.out.println("Making ticket"); this(name, 0); }
Ticket(String name, int seat) { this.name = name; this.seat = seat; }}
public class ThisFirstDemo { public static void main(String[] args) { Ticket t = new Ticket("Priya"); System.out.println(t.name); }}ThisFirstDemo.java:7: error: call to this must be first statement in constructor
this(name, 0);
^
1 errorWhat this code does
- The
printlncomes beforethis(name, 0), so the call is not the first statement. - Fix: put
this(name, 0);first and move theprintlnbelow it.
The reason: the called constructor should set the object up before any other code in the calling constructor touches it. To print a message, put it after the this(...) line.
this(...). Java 17 and most real projects follow the classic rule: this(...) first.The order things run in
Bus has a field initializer, int seats = 40;, and two chained constructors. Field initializers run once, just before the body of the constructor that does not call this(...); the constructor called by new finishes last. Step through it.
With inheritance, one more step comes first: the parent class's constructor. Constructor execution in inheritance (opens in a new tab) adds that step to this order.
Trace the code
Trace new Bus() through a chain
Variables
- seats
- 0
- route
- null
Output
(nothing printed yet)Line 18new Bus() makes the object first. Every field has its default: seats is 0 and route is null.
{ ... } block in a class body, an instance initializer block, runs at the same moment as the field initializers. It is rare; a field initializer or a constructor is clearer.No loops: recursive constructor invocation
If Fan() calls this(3) and Fan(int) calls this(), each would call the other forever. javac spots the loop and stops with recursive constructor invocation.
Example 4 · Constructors calling each other in a loop
class Fan { int speed;
Fan() { this(3); }
Fan(int speed) { this(); }}
public class LoopDemo { public static void main(String[] args) { Fan f = new Fan(); System.out.println(f.speed); }}LoopDemo.java:4: error: recursive constructor invocation
Fan() {
^
1 errorWhat this code does
Fan()callsFan(int), which callsFan()again: a chain with no end.javacrefuses it before the program ever runs.- Fix: let
Fan(int)do the work (this.speed = speed;) instead of callingthis().
Every chain must end at the full constructor: the one that does the work without calling this(...).
Fix the error
Fix the this() error
Read the error, then pick the line that fixes it.
Round 1 of 3
Pen() should set the colour to Blue and the price to 10. Pen has a Pen(String colour) constructor.
Error
error: call to this must be first statement in constructor
Next step
Check your understanding
12 quick questions