CKTIS / Java
Compact canonical constructor for a record
In Java SE 21, a record’s compact canonical constructor validates or normalizes arguments before Java assigns their values to the component fields.
Version: Java SE 21
Syntax
record R(T1 c1, T2 c2) {
R {
// Validate or normalize c1 and c2.
}
}
For a public record, declare the compact constructor as `public R { ... }`. There is no parameter list in the declaration; the call still supplies all components, as in `new R(v1, v2)`.A Record compact canonical constructor is the short form of a record’s canonical constructor. In Java SE 21, write public Person { ... } inside a public record, with no parentheses or parameter list. The parameter types, names, and order come from the record header. A call to new Person(...) still takes arguments for all components.
Inside the body, firstName names the parameter, not the field. Reassigning the parameter is allowed; assigning to a component field, as in this.firstName = firstName, is a compile-time error, as are return and explicit constructor calls using this(...) or super(...). Only when the body finishes normally does Java assign the current parameter values to the private final fields, in header order. If the body throws, those assignments do not happen.
A record has only one canonical constructor. Declare it in compact form or use the full parameter list and initialize the fields explicitly. If you declare neither form, Java supplies a canonical constructor. An explicitly declared canonical constructor cannot be less accessible than the record.
A compact constructor does not change the record’s method contract. The generated public accessors, such as firstName(), return the field values. Generated equals requires the same record class and equality of all components. Generated hashCode uses all components and must match for equal records. Generated toString includes the record name and the names and text representations of component values; its exact format is not guaranteed. Rebuilding a record from its own accessor results must produce an equal record.
Examples
import java.util.Objects;
public record Person(String firstName, String lastName, String email, int age) {
public Person {
firstName = Objects.requireNonNull(firstName, "firstName").strip();
Objects.requireNonNull(lastName, "lastName");
Objects.requireNonNull(email, "email");
if (age < 0) {
throw new IllegalArgumentException("age must be non-negative");
}
}
public static void main(String[] args) {
Person person = new Person(" Ada ", "Lovelace", "ada@example.test", 36);
Person copy = new Person(person.firstName(), person.lastName(),
person.email(), person.age());
System.out.println("firstName: " + person.firstName());
System.out.println("equal copy: " + person.equals(copy));
System.out.println("same hash: " + (person.hashCode() == copy.hashCode()));
try {
new Person("Ada", "Lovelace", null, 36);
} catch (NullPointerException e) {
System.out.println("null rejected: " + e.getMessage());
}
try {
new Person("Ada", "Lovelace", "ada@example.test", -1);
} catch (IllegalArgumentException e) {
System.out.println("invalid age rejected: " + e.getMessage());
}
}
}
Result
firstName: Ada equal copy: true same hash: true null rejected: email invalid age rejected: age must be non-negative
`Person` rejects `null` for each of the three reference parameters with `Objects.requireNonNull` (`NullPointerException`), removes leading and trailing whitespace from `firstName` with `strip()`, and rejects a negative age with `IllegalArgumentException`. It does not validate the email format. The console shows the stored normalized value, equality of the copy, matching hash codes, and rejection of a null `email` and a negative age.
Related lessons
- Java · Lesson 8 · Advanced · Version: 2