LS Price Increase Launch

The Price of all “Learn Spring” course packages will increase by $40 on next Friday:

>> GET ACCESS NOW

1. Overview

In this short tutorial, we'll see how to chain constructors in Java. It's a handy design pattern that creates less duplicated code and makes it more readable.

First, we'll explain what constructors chaining is all about. Then, we'll see how to chain them in the same class and use constructors from the parent class. Last but not least, we'll analyze the benefits and drawbacks of this approach.

2. Chaining Constructors Definition with Examples

Constructor chaining is the process of calling a sequence of constructors. We can do it in two ways:

  • by using this() keyword for chaining constructors in the same class
  • by using super() keyword for chaining constructors from the parent class

Let's see examples showing both approaches.

2.1. Chaining Constructors Within the Same Class

Let's define a simple Person class that contains a few attributes:

public class Person {
    private final String firstName;
    private final String middleName;
    private final String lastName;
    private final int age;

    //getters, equals and hashcode
}

The firstName, lastName, and age are attributes that we want to always set during object initialization. However, not every person has a middle name. Therefore the middleName attribute is optional.

With that in mind, we're going to create two constructors. The first one accepts all four attributes:

public Person(String firstName, String middleName, String lastName, int age) {
    this.firstName = firstName;
    this.middleName = middleName;
    this.lastName = lastName;
    this.age = age;
}

The second constructor is going to accept three required attributes and omit the optional field:

public Person(String firstName, String lastName, int age) {
    this(firstName, null, lastName, age);
}

We're using the this() keyword. It must always be the first line of the constructor. This ensures that the constructor that we're chaining to will be invoked in the first place.

Keep in mind that the order of constructors in class is not relevant. That means that our second constructor can be placed anywhere in the Person class, and it will still work correctly.

2.2. Chaining Constructors From the Parent Class

Let's define a Customer class that inherits from the Person class created in the previous section:

public class Customer extends Person {
    private final String loyaltyCardId;

   //getters, equals and hashcode
}

It contains an extra attribute. Now, let's create two constructors in a similar way as in the Person class:

public Customer(String firstName, String lastName, int age, String loyaltyCardId) {
    this(firstName, null, lastName, age, loyaltyCardId);
}

public Customer(String firstName, String middleName, String lastName, int age, String loyaltyCardId) {
    super(firstName, middleName, lastName, age);
    this.loyaltyCardId = loyaltyCardId;
}

The first constructor uses the this() keyword to chain to the second constructor, which accepts all required and optional attributes. Here, we use the super() keyword for the first time.

Its behavior is very similar to the this() keyword. The only difference is that super() chains to the corresponding constructor in the parent class, whereas this() chains to the constructor in the same class.

Keep in mind that similar to the previous keyword, super() must always be the first line of the constructorThis means that the parent's constructor is invoked in the first place. After that, the value is assigned to the loyaltyCardId attribute.

3. Chaining Constructors Benefits and Drawbacks

The biggest advantage of constructors chaining is less duplicated code. In other words, we use the Don't Repeat Yourself (DRY) principle. This is because we have the object's initialization done in a single constructor, typically the one accepting all attributes. Other constructors are just for passing received data and adding default values for missing attributes.

Chaining constructors makes code more readable. We don't have to repeat attribute assignments throughout all constructors. Instead, we do this in one place.

On the other hand, we expose more ways of constructing an object when using constructors chaining. This might be a significant drawback in some projects. In those cases, we should look for factory or builder patterns to hide multiple constructors.

4. Conclusion

In this article, we discussed constructors chaining in Java. Firstly, we explained what is called constructors chaining. Then, we showed how to do this with constructors within the same class as well as using parent's constructors. Finally, we discussed the benefits and drawbacks of chaining constructors.

As always, the complete source code of the article is available over on GitHub.

LS Price Increase Launch

The Price of all “Learn Spring” course packages will increase by $40 on next Friday:

>> GET ACCESS NOW
Generic footer banner
guest
0 Comments
Inline Feedbacks
View all comments