What do records (Java 16+) give you with record Point(int x, int y) {}?
Options
- A mutable class with setters for each component field
- An immutable class with getters,
equalsandtoString(Correct option) - A database table that is mapped from the components
- A class that is not allowed to declare any methods
Answer
An immutable data class with constructor, getters (x()), equals, hashCode and toString generated automatically
Why
A record is a short way to declare a plain data carrier. The compiler generates the constructor, accessors (p.x(), not getX()), equals, hashCode and toString from the listed components.
Fields are final, so records are immutable. They are ideal for DTOs, API responses and map keys. Records can still have extra methods and validation in a compact constructor.
Remember
record = immutable data class with boilerplate generated.