Video in progress
What limits do records have from an OOP point of view, and is it right to add behavior (methods) to them?
A record is final, can't extend another class, can't add instance fields, and all its components are public. But you can add methods, static factories and interfaces, and you often should: a record is not just a "data box".
📖 Answer
A record's limits:
- implicitly
final, so you can't inherit from it; - implicitly
extends java.lang.Record, so it can't extend another class, only implement interfaces; - no instance fields other than the declared components (static ones are fine);
- fields are
private finaland accessors arepublic, so you can't hide the state; - it can't be a JPA entity: Hibernate needs a mutable, proxyable class.
Adding behavior, though, is normal and useful:
public sealed interface Shape permits Circle, Rect {}
public record Rect(double w, double h) implements Shape {
public Rect {
if (w <= 0 || h <= 0) throw new IllegalArgumentException();
}
public static Rect square(double side) { return new Rect(side, side); }
public double area() { return w * h; }
public Rect scale(double k) { return new Rect(w * k, h * k); }
}
A common interview mistake: "a record is only for DTOs". In fact a record is ideal for value objects: immutable, correct equals/hashCode, validation in the compact constructor.
When a record doesn't fit: when you need to hide state (for example an internal cache or a lazily computed value), when there's a complex relationship between fields and some fields are derived, or when the API is likely to change later, because adding a component changes the canonical constructor and breaks all callers.
Sign up to mark studied questions and save your progress.