Records

A short immutable data carrier.

A record is a compact class for data that does not change. record User(String name, int age) {} creates the fields, the constructor, name(), age(), equals, hashCode and toString by itself. Writing all of that by hand for a couple of fields is noise in which equals is easy to forget.

A component is read through the method name(), not a field. Records are immutable: there is no new name, there is a new User. For a request, a response or a key this is a good shape. For an object with behaviour and hidden rules, an ordinary class is more honest.

In a training program a record can be declared inside Main. In a real service it goes into its own file if it is public. Same package, same visibility rules.

Do not make a record with a dozen components and half a screen of logic. Once checks, branches and queries show up, it is a class. A record answers "which fields arrived" well and "what is this object allowed to do" badly.

Practice

  1. How to read the name

    For record User(String name, int age), how do you read the name?

    • user.name()
    • user.getNameField
    • User.name
    • name.user
  2. What to print

    The name is Ann and the age is 20. In the task, the name and age are joined with a colon. Write the line.

  3. A short record

    Declare a record with a name and an age, create Ann and 20, and print Ann:20.