Understanding Records in Java

Introduced in Java 14 as a preview feature and officially added in Java 16, records are a special kind of class in Java designed to model immutable data. They significantly reduce boilerplate code for classes that are primarily used to store data.

What is a Record?

A record is a final class that implicitly provides implementations for equals(), hashCode(), and toString(). The primary goal is to simplify the creation of data-carrying classes.

Syntax

public record Person(String name, int age) {}

This single line defines a class with:

  • Private final fields name and age
  • A canonical constructor
  • Getters for each field (e.g., name() and age())
  • Implementations of equals(), hashCode(), and toString()

Example Usage


Person p = new Person("Alice", 30);
System.out.println(p.name());   // Alice
System.out.println(p);          // Person[name=Alice, age=30]
  

Why Use Records?

Records offer several benefits:

  • Concise syntax
  • Immutability by default
  • Built-in methods (constructor, equals, hashCode, toString)
  • Improved readability and maintainability

Limitations

  • Records are implicitly final – they cannot be extended.
  • Fields are final – values cannot be changed after construction.
  • You cannot declare instance fields outside the record header.

Customizing Records

You can add methods or customize the constructor, but you must respect the immutability contract:


public record Point(int x, int y) {
    public Point {
        if (x < 0 || y < 0) {
            throw new IllegalArgumentException("Coordinates must be non-negative");
        }
    }

    public int sum() {
        return x + y;
    }
}
  

Conclusion

Java records provide a powerful, elegant solution for defining data classes with minimal code. If your class is just a data holder, records are likely the best tool for the job.

Post a Comment

0 Comments