Records in java
Basu
Posted on March 26, 2024
Whenever we talk about boilerplate code in Java, there is always an argument that now IDEs are intelligent enough to generate sources. The problem comes when there is an addition in the fields. Record
in Java 14 solves this problem at least for the Data Classes.
A record class in Java automatically has:
- A private final field for each component of the record.
- A public constructor whose signature matches the record components.
- Public read accessor methods for each component of the record, with the same name and type as the component.
- Implementations of equals(), hashCode(), and toString() methods.
Here is an example of how to declare and use a record:
public record Employee(String name, int age) {}
This record class Employee has two components: name and age. You can create an instance of Employee and access its components like this:
Employee employee = new Employee("John Doe", 30);
System.out.println(employee.name()); // prints "John Doe"
System.out.println(employee.age()); // prints 30
Note that records are intended to be used as simple data carriers, so they are not suitable for every situation. If you need more complex behavior, you should use a regular class.
Records in Java, while useful for creating simple data carrier classes, do have some limitations:
- No Inheritance: Records cannot extend any other class, and they are implicitly final, so no other class can extend a record.
- Limited Instance Variables: All instance variables must be declared in the record header, and these variables are automatically final. You cannot declare additional fields in the body of the record.
- No Argument-less Constructor: Records automatically provide a constructor with arguments for all fields, but they do not provide a no-argument constructor. This can be a limitation when working with frameworks that rely on no-argument constructors.
- No Mutability: Since all fields in a record are final, records are inherently immutable. This means once a record object is created, you cannot change its state.
- Limited Use of Annotations: Annotations that are applicable to classes, methods, or fields may not be applicable to record components.
- Limited Scope: Records are intended to be used as simple data carriers. If you need more complex behavior, such as methods that operate on the fields, you should use a regular class.
few good reads -
Posted on March 26, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.