Skip to main content

Employ Java Records

If you are using Java 15 or above - use records in your modelling classes. Records are a type of class enabling the easy creation of immutable data objects.

// Prior to Java 15
public class Employee {
private final int age;
private final String name;

public Employee(int age, String name) {
this.age = age;
this.name = name;
}

public int getAge() { return age; }
public void getName(String name) { return name; }
}
// With Java 15
public record Employee(int age, String name) {}

The record has the following properties:

  1. The member accessors are provided by default with the record keyword (without a get prefix)
  2. All members are declared final
  3. A constructor is no longer required (instantiation being the same as the initial example), with the signature derived from the member variables.
  4. equals() and hashCode() are implemented by default, specifying 2 records equal if they have the same type and each member variable is equal.
  5. toString() results in the member variables outputted in square bracket form ([age=15, name="Clem Fandango"])

Custom Constructor

A custom constructor can also be included with custom arguments:

public record Employee(int age, String name) {
public Employee(String name) {
this(99, name);
}

public Employee(int age) {
this.age = 75;
this.name = "Charles Dance";
}
}

Static Variables & Methods

Similarly to standard Java classes - static variables and methods can be included inside Java records.

public record Employee(int age, String name) {
public static String REFERENCE = "B12-GHI";

public static int dummyEmployee() {
return new Employee(75, "John Doe");
}
}

class TestRecord {
public void getRecordDetails() {
log(Employee.REFERENCE);
log(Employee.dummyEmployee().age());
}
}