From ChatGPT and this post.
In a record type, the appropriate accessors, constructor, equals, hashCode, and toString methods are created automatically.
Record type is used for immutable data. It means all record fields in it are final, and they can only be set within a constructor, either a “cononical constructor”(set all fields explicitly) or an “overloaded constructor”(set all fields with given field value(s) and the default value(s)). No-argument constructor is not allowed since it doesn’t make sence for immutable data.
Compact Constructor can be used to perform extra validation, transformation, or initialization logic.
1
2
3
4
5
6
7
8
9
10
11public record Person(String name, int age) {
// Canonical constructor is automatically provided
// Compact constructor (custom constructor)
public Person {
if (age < 0) {
throw new IllegalArgumentException("Age cannot be negative");
}
}
}Record type cannot extend from other class(including another record type) or be extended by other subclass(including another record type), while it can implement interface, and can be a filed of another record type. You can take it as a special “final” class.
You cannot declare instance variables (non-static fields) or instance initializers in a record class.
Another post is also a good one for Java local variable type inference.