92. Defining multiple constructors in a record
As you know, when we declare a Java record, the compiler uses the given components to create a default constructor known as the canonical constructor. We can also provide an explicit canonical/compact constructor, as you saw in Problem 89.
But, we can go even further and declare more constructors with a different list of arguments. For example, we can have a constructor with no arguments for returning a default instance:
public record MelonRecord(String type, float weight) {
private static final String DEFAULT_MELON_TYPE = "Crenshaw";
private static final float DEFAULT_MELON_WEIGHT = 1000;
MelonRecord() {
this(DEFAULT_MELON_TYPE, DEFAULT_MELON_WEIGHT);
}
}
Or, we can write a constructor that gets only the melon’s type or the melon’s weight as an argument:
public record MelonRecord(String type, float weight) {
private static final String DEFAULT_MELON_TYPE = "Crenshaw";...