Record (preview từ Java 14, chính thức từ Java 16) là loại class đặc biệt dành cho dữ liệu thuần túy — immutable data carrier.
Khai báo: record Person(String name, int age) {}.
Compiler tự sinh: constructor, getters (name(), age()), equals(), hashCode(), toString().
So với POJO thông thường: ít boilerplate hơn rất nhiều.
Khi nên dùng:
- DTO (Data Transfer Objects) — dữ liệu giữa các layer.
- Value objects.
- API response/request model.
- khi cần immutability rõ ràng
Record Patterns (Java 21): deconstruct trực tiếp trong switch/instanceof — if (obj instanceof Person(String name, int age)) { ... }.
Hạn chế: không extend class (chỉ implement interface), không thêm mutable field.