With Record class type, various terminologies are introduced to Java developers. Compact constructor is one of them, and well known all-args constructor or all fields constructor is called a canonical constructor. Aside from these two constructor types, there is another type called a custom constructor for record classes. In the following sections, I’ll describe them with examples.
If you don’t have a medium membership, you can use this link to reach the article without a paywall.
Canonical Constructor
Almost every developer knows the canonical constructor type. It is the all-args constructor. In my previous record class type blog posts, I have used the canonical constructor to show examples. You can check them too. Their links are at the end of this post.
By writing a canonical constructor, you can manipulate the args and set the fields as you wish. In the below example, we intended to trim the name argument and convert the email argument to lowercase.
public record UserRecord(String name, int age, String email) {
public UserRecord(String name, int age, String email) {
this.name = name.trim();
this.age = age;
this.email = email.toLowerCase(Locale.ROOT);
}
}