Bird
Raised Fist0
Javaprogramming~5 mins

Constructor chaining in Java

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction

Constructor chaining helps reuse code inside a class by calling one constructor from another. It makes creating objects easier and avoids repeating code.

When you have multiple constructors with different parameters but similar setup steps.
When you want to provide default values for some parameters while allowing others to be set.
When you want to simplify object creation by reusing existing constructor logic.
When you want to keep your code clean and avoid duplication in constructors.
Syntax
Java
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.

Examples
This example shows three constructors. The default constructor calls the single-parameter constructor, which calls the three-parameter constructor. This avoids repeating code.
Java
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
    }
}
Here, constructors chain to provide default values for missing parameters.
Java
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
    }
}
Constructor chaining is optional. If you don't need it, constructors can be independent.
Java
public class EmptyExample {
    public EmptyExample() {
        // No chaining here
    }
}
Sample Program

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.

Java
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();
    }
}
OutputSuccess
Important Notes

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.

Summary

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

(1/5)
1. What is the main purpose of constructor chaining in Java?
easy
A. To allow one constructor to call another constructor in the same class
B. To inherit constructors from a parent class automatically
C. To create multiple objects with the same constructor
D. To override constructors with different names

Solution

  1. Step 1: Understand constructor chaining concept

    Constructor chaining means one constructor calls another constructor in the same class to reuse code.
  2. Step 2: Identify the correct purpose

    To allow one constructor to call another constructor in the same class correctly describes this behavior using this(...) to call another constructor.
  3. Final Answer:

    To allow one constructor to call another constructor in the same class -> Option A
  4. Quick Check:

    Constructor chaining = calling another constructor [OK]
Hint: Constructor chaining uses this(...) to call another constructor [OK]
Common Mistakes:
  • Confusing constructor chaining with inheritance
  • Thinking constructors can have different names
  • Believing constructor chaining creates multiple objects
2. Which of the following is the correct syntax to chain constructors in Java?
easy
A. this.call(); // calls another method
B. super(); // calls constructor of same class
C. this(); // must be the first statement in constructor
D. constructor(); // calls constructor by name

Solution

  1. Step 1: Recall syntax for constructor chaining

    Constructor chaining uses this(...) as the first statement inside a constructor.
  2. Step 2: Identify correct option

    this(); // must be the first statement in constructor shows this(); which is the correct syntax to call another constructor in the same class.
  3. Final Answer:

    this(); // must be the first statement in constructor -> Option C
  4. Quick Check:

    Constructor chaining syntax = this() first [OK]
Hint: Use this() as first line to chain constructors [OK]
Common Mistakes:
  • Using super() to call same class constructor
  • Calling constructor by its name directly
  • Placing this() after other statements
3. What will be the output of the following Java code?
class Test {
  Test() {
    this(5);
    System.out.print("A");
  }
  Test(int x) {
    System.out.print("B");
  }
  public static void main(String[] args) {
    new Test();
  }
}
medium
A. AB
B. BA
C. A
D. B

Solution

  1. Step 1: Trace constructor calls

    Creating new Test() calls the no-arg constructor, which calls Test(int x) first (prints "B"), then prints "A".
  2. 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".
  3. Final Answer:

    BA -> Option B
  4. Quick Check:

    Constructor chaining prints B then A [OK]
Hint: Constructor chaining prints inner constructor output first [OK]
Common Mistakes:
  • Assuming outer constructor prints before inner
  • Confusing order of constructor calls
  • Ignoring that this() must be first line
4. Identify the error in the following Java code related to constructor chaining:
class Sample {
  Sample() {
    System.out.println("Hello");
    this(10);
  }
  Sample(int x) {
    System.out.println(x);
  }
}
medium
A. Constructor chaining call this(10) must be the first statement
B. Constructor name must match class name
C. Cannot overload constructors with different parameters
D. Missing return type in constructors

Solution

  1. Step 1: Check constructor chaining rules

    In Java, the call to another constructor using this(...) must be the first statement in the constructor.
  2. Step 2: Identify the error

    Here, System.out.println("Hello") comes before this(10);, which violates the rule.
  3. Final Answer:

    Constructor chaining call this(10) must be the first statement -> Option A
  4. Quick Check:

    this() must be first line in constructor [OK]
Hint: this() call must be first statement in constructor [OK]
Common Mistakes:
  • Placing code before this() call
  • Confusing constructor overloading with chaining
  • Thinking constructors need return types
5. Given the class below, what will be the output when 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");
  }
}
hard
A. ZXY
B. ZY
C. XYZ
D. ZYX

Solution

  1. Step 1: Trace constructor chaining calls

    Calling new Box() calls no-arg constructor, which calls Box(int w, int h), which calls Box(int w, int h, int d).
  2. 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".
  3. Final Answer:

    ZYX -> Option D
  4. Quick Check:

    Chained constructors print Z then Y then X [OK]
Hint: Deepest constructor prints first, then unwind chain [OK]
Common Mistakes:
  • Assuming outer constructor prints first
  • Ignoring chaining order
  • Mixing up print order in nested calls