record (Java)
A compact Java class for plain data, declared with its components in one line, for which the compiler generates the fields, accessors, equals, hashCode and toString.
In more detail
Each component becomes a private final field with an accessor of the same name, so a record is shallowly immutable. Records cannot extend another class and are meant for transparent data such as request and response models. Validation goes in a compact constructor, and records can still have methods that derive views of their data. Records have been standard since Java 16.
Examples
public record Point(int x, int y) { }public record OrderSummary(String id, int itemCount, String status) { }Related terms
- compact constructor — A record constructor written without a parameter list, which runs checks before the record's fields are assigned.
- accessor method — A method that returns the value of a field, such as id() on a record or getId() on a JavaBean-style class.
- immutable — Something that cannot be changed after it is created; to change it you make a new one.
- equals method — The method that decides whether two objects hold the same value, as opposed to == which checks whether they are the same object.
- class — A blueprint in code that bundles data and the functions that work on it, from which objects are made.
Taught in
- Primitive And Reference Types — Modern Java: Virtual Threads & High-Throughput Services
- Records And Data Classes — Modern Java: Virtual Threads & High-Throughput Services
- Sealed Types And Exhaustiveness — Modern Java: Virtual Threads & High-Throughput Services
- Working With Jackson — Modern Java: Virtual Threads & High-Throughput Services
- Configuration And Profiles — Modern Java: Virtual Threads & High-Throughput Services
- Validation — Modern Java: Virtual Threads & High-Throughput Services