Sage-Code Laboratory
index<--

Records

JDK 14 introduces records, which are a new kind of type declaration. Like an enum, a record is a restricted form of a class. It’s ideal for "plain data carriers," classes that contain data not meant to be altered and only the most fundamental methods such as constructors and accessors.
// declare simpe record Rectangle
record Rectangle(double length, double width) { }

// use record defined previously
Rectangle r = new Rectangle(4,5);

Notes:

A record class declares the following members automatically:

  1. For each component in the header, the following two members:
  2. A private final field with the same name and declared type as the record component. This field is sometimes referred to as a component field.
  3. A public accessor method with the same name and type of the component; in the Rectangle record class example, these methods are Rectangle::length() and Rectangle::width().
  4. A canonical constructor whose signature is the same as the header. This constructor assigns each argument from the new expression that instantiates the record class to the corresponding component field.
  5. Implementations of the equals and hashCode methods, which specify that two record classes are equal if they are of the same type and contain equal component values.
  6. An implementation of the toString method that includes the string representation of all the record class's components, with their names.
Using record is almost too easy. However sometimes you want to implement your own constructors, or field setters with validations. To learn how to do these things you need to read the Oracle manual for specific JDK version.

See also:JDK19: Records manual


Read next: Sealed Classes