Constructor chaining helps reuse code inside a class by calling one constructor from another. It makes creating objects easier and avoids repeating code.
Constructor chaining in Java
Start learning this pattern below
Jump into concepts and practice - no test required
public class ClassName { // Constructor with parameters public ClassName(Type1 param1, Type2 param2) { // initialization code } // Constructor chaining: calling another constructor public ClassName(Type1 param1) { this(param1, defaultValueForParam2); // calls the other constructor } }
Use this(...) to call another constructor in the same class.
The call to this(...) must be the first statement in the constructor.
public class Box { int width, height, depth; // Constructor with all dimensions public Box(int width, int height, int depth) { this.width = width; this.height = height; this.depth = depth; } // Constructor chaining: cube with equal sides public Box(int side) { this(side, side, side); // calls the 3-parameter constructor } // Default constructor public Box() { this(1); // calls the single parameter constructor } }
public class Person { String name; int age; public Person(String name, int age) { this.name = name; this.age = age; } public Person(String name) { this(name, 0); // default age 0 } public Person() { this("Unknown"); // default name } }
public class EmptyExample { public EmptyExample() { // No chaining here } }
This program shows constructor chaining in the Car class. Different constructors call each other to set default values. The main method creates cars with different constructors and prints their details.
public class Car { String brand; String model; int year; // Constructor with all parameters public Car(String brand, String model, int year) { this.brand = brand; this.model = model; this.year = year; } // Constructor chaining: default year public Car(String brand, String model) { this(brand, model, 2024); // default year } // Constructor chaining: default brand and year public Car(String model) { this("Unknown", model, 2024); } // Default constructor public Car() { this("Unknown", "Unknown", 2024); } public void printDetails() { System.out.println("Brand: " + brand + ", Model: " + model + ", Year: " + year); } public static void main(String[] args) { Car car1 = new Car("Toyota", "Corolla", 2020); Car car2 = new Car("Honda", "Civic"); Car car3 = new Car("Mustang"); Car car4 = new Car(); System.out.println("Before constructor chaining:"); car1.printDetails(); car2.printDetails(); car3.printDetails(); car4.printDetails(); } }
Constructor chaining improves code reuse and reduces errors by centralizing initialization.
Time complexity is not affected by chaining; it is just a call to another constructor.
Common mistake: forgetting that this(...) must be the first statement in the constructor.
Use constructor chaining when you want to provide multiple ways to create an object with some default values.
Constructor chaining lets one constructor call another to reuse code.
Use this(...) as the first line in a constructor to chain.
It helps keep code clean and avoid repeating initialization steps.
Practice
Solution
Step 1: Understand constructor chaining concept
Constructor chaining means one constructor calls another constructor in the same class to reuse code.Step 2: Identify the correct purpose
To allow one constructor to call another constructor in the same class correctly describes this behavior usingthis(...)to call another constructor.Final Answer:
To allow one constructor to call another constructor in the same class -> Option AQuick Check:
Constructor chaining = calling another constructor [OK]
- Confusing constructor chaining with inheritance
- Thinking constructors can have different names
- Believing constructor chaining creates multiple objects
Solution
Step 1: Recall syntax for constructor chaining
Constructor chaining usesthis(...)as the first statement inside a constructor.Step 2: Identify correct option
this(); // must be the first statement in constructor showsthis();which is the correct syntax to call another constructor in the same class.Final Answer:
this(); // must be the first statement in constructor -> Option CQuick Check:
Constructor chaining syntax = this() first [OK]
- Using super() to call same class constructor
- Calling constructor by its name directly
- Placing this() after other statements
class Test {
Test() {
this(5);
System.out.print("A");
}
Test(int x) {
System.out.print("B");
}
public static void main(String[] args) {
new Test();
}
}Solution
Step 1: Trace constructor calls
Creating new Test() calls the no-arg constructor, which calls Test(int x) first (prints "B"), then prints "A".Step 2: Determine output order
Since Test(int x) prints "B" first, then control returns to no-arg constructor which prints "A", output is "BA".Final Answer:
BA -> Option BQuick Check:
Constructor chaining prints B then A [OK]
- Assuming outer constructor prints before inner
- Confusing order of constructor calls
- Ignoring that this() must be first line
class Sample {
Sample() {
System.out.println("Hello");
this(10);
}
Sample(int x) {
System.out.println(x);
}
}Solution
Step 1: Check constructor chaining rules
In Java, the call to another constructor usingthis(...)must be the first statement in the constructor.Step 2: Identify the error
Here,System.out.println("Hello")comes beforethis(10);, which violates the rule.Final Answer:
Constructor chaining call this(10) must be the first statement -> Option AQuick Check:
this() must be first line in constructor [OK]
- Placing code before this() call
- Confusing constructor overloading with chaining
- Thinking constructors need return types
new Box(); is executed?class Box {
Box() {
this(3, 4);
System.out.print("X");
}
Box(int w, int h) {
this(w, h, 5);
System.out.print("Y");
}
Box(int w, int h, int d) {
System.out.print("Z");
}
}Solution
Step 1: Trace constructor chaining calls
Callingnew Box()calls no-arg constructor, which callsBox(int w, int h), which callsBox(int w, int h, int d).Step 2: Track printed characters in order
The deepest constructor prints "Z" first, then returns to middle constructor which prints "Y", then returns to no-arg constructor which prints "X".Final Answer:
ZYX -> Option DQuick Check:
Chained constructors print Z then Y then X [OK]
- Assuming outer constructor prints first
- Ignoring chaining order
- Mixing up print order in nested calls
