Java Intermediate

0% completed

Previous
Next
Constructor Chaining By Using this Keyword

What is Constructor Chaining?

Constructor chaining is the process of calling one constructor from another constructor within the same class using the this keyword. It helps in reducing code duplication and streamlining object initialization.

  • Characteristics:
    • Achieved using this() with appropriate parameters.
    • Must be the first statement in the constructor.
    • Allows multiple constructors to build upon each other.

Syntax of Constructor Chaining with this Keyword

class ClassName { // Constructor 1 ClassName() { // Initialization code } // Constructor 2 calling Constructor 1 ClassName(dataType parameter) { this(); // Calls Constructor 1 // Additional initialization code } // Constructor 3 calling Constructor 2 ClassName(dataType parameter1, dataType parameter2) { this(parameter1); // Calls Constructor 2 // Additional initialization code } }

Explanation:

  • this(): Invokes another constructor in the same class without parameters.
  • this(parameter): Invokes another constructor in the same class with the specified parameters.
  • Positioning: The call to this() or this(parameters) must be the first statement in the constructor.
Image

Example 1: Car Class Using Constructor Chaining

In this example, the Car class demonstrates constructor chaining by having multiple constructors that call each other using the this keyword.

Java
Java

. . . .

Explanation:

  • Car():

    • Calls this("Unknown Brand"), invoking the second constructor.
    • Prints "Default constructor called."
  • Car(String brand):

    • Calls this(brand, "Unpainted"), invoking the third constructor.
    • Prints "Constructor with brand called."
  • Car(String brand, String color):

    • Initializes brand and color with provided values.
    • Sets year to 0.
    • Prints "Constructor with brand and color called."
  • Object Creation:

    • Car defaultCar = new Car();
      • Triggers the default constructor, which chains to the second and then the third constructor.
    • Car brandCar = new Car("Ford");
      • Triggers the second constructor, which chains to the third constructor.
    • Car detailedCar = new Car("BMW", "Black");
      • Directly triggers the third constructor.

Constructor chaining is a powerful feature in Java that allows one constructor to invoke another within the same class using the this keyword. This approach promotes code reusability, reduces duplication, and provides flexibility in object initialization. Through the Car class examples, we've seen how multiple constructors can be linked together to initialize objects with varying degrees of detail. Understanding constructor chaining enhances your ability to design clean, efficient, and maintainable classes in Java.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next