Records

A record is a concise class for data whose identity is its component values. Java generates a constructor, accessors, equals, hashCode, and toString.

Records remove repetitive code from immutable data carriers such as coordinates or color values. Their component fields cannot be reassigned after construction.

Model a small value

record Coordinate(int row, int column) {}

public class Main {
    public static void main(String[] args) {
        Coordinate first = new Coordinate(2, 5);
        Coordinate second = new Coordinate(2, 5);
        System.out.println(first);
        System.out.println(first.row());
        System.out.println(first.equals(second));
    }
}

Output:

Coordinate[row=2, column=5]
2
true

The generated text representation names both components. Each component also gets an accessor method with the same name, so first.row() returns 2. There is no get prefix on record accessors. Records also compare their component values, so the two separately created coordinates are equal.

A record can validate constructor arguments and define methods. It is a poor fit when the object needs mutable identity or an inheritance hierarchy.

Complete the Player record and use its generated name and level accessors.