Java 14 arrived a few weeks ago and introduces the Record type, which is an immutable data carrier class designed to hold a fixed set of fields. Note that this is a preview language feature, which means that it must be explicitly enabled in the Java compiler and runtime using the
I’m going to jump straight in with an example of a
Book record designed to hold the title, author, publish date and price of a book. This is how the record class is declared:
You can use
javap to see the code that the compiler has autogenerated:
As shown above, the compiler has automatically generated the constructor, getter methods,
toString, thus saving us from having to type a lot of boilerplate code.
However, records do not just save on typing. They also make your intent clear that you want to model an immutable data item as a group of related fields.
Compact Constructors for Field Validation
Now let’s say that you want to add validation and default values to your record. For example, you might want to validate that
Book records are not created with negative prices or future publish dates. This can be done with a compact constructor as shown below:
The compact constructor does not have a parameter list. It validates the price and publish date, and also sets a default value for the author. The fields that have not been assigned in this constructor (i.e.
price) are implicitly initialised at the end of this constructor.
Alternative Constructors and Additional Methods
Records allow you to define additional methods, constructors, and static fields, as shown in the code below. However, remember that semantically a record is designed to be a data carrier, so if you feel that are adding extra methods, it might be that you need a class instead of a record.
Opinions expressed by Java Code Geeks contributors are their own.