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:
import java.time.LocalDate;
public class Animal {
private String name;
private LocalDate dateOfBirth;
}
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:
public Animal(String name, LocalDate dateOfBirth) {
this.name = name;
this.dateOfBirth = dateOfBirth;
}
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(...):
public Animal(String name) {
this(name, LocalDate.now());
}
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:
@Override
public String toString() {
return name + ", born " + dateOfBirth;
}
Now we can create a couple of Animal objects using the different constructors:
Animal dog = new Animal("My dog", LocalDate.of(2023, 4, 1));
System.out.println(dog);
Animal cat = new Animal("My cat");
System.out.println(cat);
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):
My dog, born 2023-04-01 My cat, born 2023-04-26
Comments