Custom Canonical constructor in Record

In the previous post under Java Record, I mentioned how the compiler creates a long (canonical) constructor automatically.

In this post, I will explain how to create a custom canonical constructor.

Now why we need to provide a custom canonical constructor when it is already provided by compiler.

The canonical constructor created by compiler will take input arguments and set it to Record instance fields

So if we have a Record named “Account” with instance fields named “id”, “name”, and “amount”, the canonical constructor will be as shown below

    public Account(int id, String name, long amount) {
        this.id = id;
        this.name = name;
        this.amount = amount;
    }

What if we want to add our own logic to the above code for example, code for input validation. We cannot do it.

To have a custom logic in a constructor, we create a constructor which is similar to compiler added canonical constructor but also has our own logic.

In our example if we want to add input validation, we will add our own constructor in the Record.java class as shown below

    public Account(int id, String name, long amount) {
        if(amount < 500) {
            throw new IllegalArgumentException("Amount less than 500");
        }
        this.id = id;
        this.name = name;
        this.amount = amount;
    }

As you can see above it is similar to compiler added canonical constructor but this time with input validation code.

In this way we can add a custom canonical constructor in Record.

Below is the class structure of Account pojo class for your reference

Account

package core.record;

public record Account(int id, String name, long amount) {
    public Account(int id, String name, long amount) {
        if(amount < 500) {
            throw new IllegalArgumentException("Amount less than 500");
        }
        this.id = id;
        this.name = name;
        this.amount = amount;
    }
}

Below is the main class for your reference

Main class

package core.record;

public class Example3 {
    public static void main(String[] args) {
        Account account1 = new Account(1, "Sam Fisher", 600);
        Account account2 = new Account(2, "Sam Manekshaw", 400);
    }
}

Leave a comment