Member-only story

Java Records

Evren Tan
2 min readOct 24, 2021

--

Java Record is a new way to declare a class to pass immutable data. Records were first introduced in Java 14 but they become more common within Java 15. So where they are used and what are their advantages?

Java Records
Java Records

Before Java records, a class should be created with boilerplate fields and methods in order to pass immutable data between objects. With record keyword, these boilerplate fields and methods are discarded and all are done with just a declaration.

So, what you can do with a record object;

  • One common public constructor with all properties in the record is automatically generated
  • All properties in the record are marked as private final automatically
  • Getter methods for all properties are automatically created
  • toString, hashCode, equals methods are created automatically
  • Properties can be decorated with annotations like validity check annotations

But you cannot extend other classes within a record object.

Now, let’s go over a code examples to deep dive in record functionality in java. Within the code, you can see the difference between an old school way of declaring a class, declaring a class with Lombok library and declaring the same class with record keyword.

Also, you can find a full Java project structure in my GitHub account within java-record-example repository.

Old School Class Declaration

Let’s start with old school way to declare a class to model a simple enterprise example.

As you can see from the code snippet, you need to;

  • Define constructor method
  • Define getter methods for all properties
  • Define toString, hashCode, equals methods

All definitions are done 50 lines of code.

Class Declaration with Lombok

--

--

Written by Evren Tan

Software Crafter | VP of DevOps at Pointr | Community Lead of Türkiye Java Community | Java & DevOps Enthusiast | Sailor | Oliver Farmer

Responses (1)

Write a response