By Tony Bevis on Wednesday, 26 April 2023
Category: Java

Constructor chaining in Java

While Java doesn't support default values for parameters, we can use chaining to achieve this within constructors.

Let's define a simple Java class called Animal that has two instance variables, the first for the animal's name and the other its date of birth:

The first step is to declare a constructor that requires all parameter values to be supplied, in our case being both the name and date of birth:

We can now consider which parameter can have a sensible default value. Here, we could default the date of birth to being today's date.

All we need to do is define a second constructor that only takes a name parameter, and which then chains this to the main constructor through the use of this(...):

When this(name, LocalDate.now()) is processed it will find the constructor that accepts two parameters and pass the values through to it.

We can test our constructors by calling each one. To make this easier to demonstrate, let's firstly add a simple toString() method that formats the object content:

Now we can create a couple of Animal objects using the different constructors:

This should result in the following output. (The one for cat will of course show the date you run the code rather than the date shown below):

Related Posts

Leave Comments