Records (Java 14)

ADITYA SHARMA
Xebia Engineering Blog

--

In this blog, we will cover one of the most exciting features that Java 14 has for developers, like Records.

Imagine we need to store data per person. Its simple we create a class Person and have two fields inside it: Name, Age. We will create constructors to initialise the values to the variables and also define getters setters, equals, toString() function, and hashcode().

But the question arises, how any other developer will know that this class is just a carrier of data without reading all the code. Records help to achieve such features like reducing the amount of code that we have to write and also makes code look cleaner.

When we compile a record, instance variables and above stated necessary methods are automatically added to it.

We can create a record by using the below code.

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

In the compiled version the Person class will be final and will extend java.lang.Record class with instance variables as final and having constructors, getters, etc.

A record can be instantiated by using “new” keyword.

Person person = new Person(“Ram”. 22);

A record can implement interfaces. We can add static fields and instance or static methods to a record if we need them.

We can also add annotations like @NotNull to record components as shown below.

public record Person(@NotNull String name. int age) {}

This will give an indication to us that the name field cannot be null and we need to pass a valid data inside it.

A record cannot be defined as an abstract class because it is implicitly a final class.

A class that is defined as a record cannot extend another class since it already extends java.land.Record class

We cannot add any instance variables to it. The state of a record is defined by the components we have in its definition.

By implementing the Serializable interface we can read or write records to a file

public record Person(String name. int age) implements Serializable {}

The creation of Generic records is also possible as shown below.

public record Person<T>(T content, String name. int age) {}

And use it as shown below:

Person<Data> person = new Person(new Data(), “Ram”. 22);

However, we can still override methods based on our requirements as shown below:

Hence we can conclude that the new feature, Record in Java 14 helps us to do everything that we needed in order to create a class, whose sole purpose was to store records. But we can now write much cleaner code without any need of writing other methods like toString(), hashcode(), getters, etc. And other developers can easily understand just by looking at a class and know that this class is used to create records and the need for reading complete code will be reduced.

--

--