Thursday, 21 March 2024

Records in java, canonical constructor & compact constructor using java

 Record is a certain type of  class. It is also special type of class.

We can create recording like below

public record EmployeeRecord(String name, int employeeNumber) {

}


We can access the name, employeeNumber, as below

For Example: EmployeeRecord record = new EmployeeRecord("Dinesh", 24);

record.name();

record.employeeNumber();


- if you declare record instance variables are final by default. 

- toString(), hashCode() & equal() are overrided automatically.

- We can't extend any class or record 

- we can implement the interface at end before flower braces

- By default the records is final. we don't required to declare final variable.

- By default Canonical Constructor is created. 

 - We can declare the variable with static final 

- we can declare the static methods 

Canonical Constructor is a constructor that is created with all instance fields as a parameters 

for example from above code 

    public EmployeeRecord (String name, int employeeNumber ) {

        this.name = name;

        this.employeeNumber = employeeNumber;

    }

- if you want override constructor you can do. Why do we required to override constructor is if need to do some validation like age should not be negative then you can throw exception if required.

- We can use Compact Constructor instead of overriding it.

What is the Compact Constructor?

  Compact Constructor with our argument or bracket we can declare need to declare as below

public EmployeeRecord {

     if (employeeNumber < 0) {

        throw new ILegalArgumentException("Not valid number");

    }

}


No comments:

Post a Comment