Classes

Java Records

Using Records

Java records provide immutable data since Java 14.

Introduction to Java Records

Java Records, introduced in Java 14, provide a compact syntax for declaring classes that are transparent holders for immutable data. They reduce the boilerplate code associated with plain old Java objects (POJOs). Records are ideal for modeling data that is purely data-centric, with no additional behavior.

Defining a Record

To define a record in Java, you use the record keyword followed by the record name and a list of components. These components automatically generate a constructor, accessors, equals(), hashCode(), and toString() methods.

Features of Java Records

  • Immutable Data: Once created, the values of a record's fields cannot be changed.
  • Automatic Method Generation: Records automatically generate essential methods like equals(), hashCode(), and toString().
  • Compact Syntax: Records reduce boilerplate code, offering a concise way to define data-carrying classes.

Using Accessor Methods

Each component of a record has a public accessor method that allows retrieving its value. This replaces the need for explicitly defined getter methods.

Customizing a Record

While records automatically generate several methods, you can still customize them if needed. For instance, you can add custom methods or override the default behavior of generated methods.

Limitations of Java Records

  • Immutability: The fields of a record are final, which means they do not support mutable data.
  • No Inheritance: Records cannot extend other classes (all records implicitly extend java.lang.Record).
  • Data-centric: Records are not suitable for defining classes that require significant behavior or mutable state.

Conclusion

Java Records provide a modern approach to creating immutable data classes with less boilerplate. They are best suited for applications where data transparency and immutability are priorities. While they come with limitations, such as lack of mutability and inheritance, their benefits in simplifying data handling are significant.

Previous
Enums