Records and Sealed Classes
Go deep on Records and Sealed Classes: edge cases, scalability limits, and how you'd evolve the solution over 2 years.
Answers use simple, clear English.
Quick interview answer
record Point(int x, int y) generates constructor, equals, hashCode, toString. sealed permits restricts subclasses — exhaustive pattern switch in Java 21+.
Detailed answer
record Point(int x, int y) generates constructor, equals, hashCode, toString. sealed permits restricts subclasses — exhaustive pattern switch in Java 21+. Scale limits often appear in: Records shallowly immutable — mutable fields inside break contract.. Evolution levers: Use compact constructor to validate; combine sealed + records for domain ADTs.. Anchor example: API result type: sealed interface Result permits Success, Failure with record payloads. Core: record Point(int x, int y) generates constructor, equals, hashCode, toString. sealed permits restricts subclasses — exhaustive pattern switch in Java 21+. Real-time example: API result type: sealed interface Result permits Success, Failure with record payloads. Pros: Less boilerplate; algebraic modeling with compiler-checked exhaustiveness. Cons: Records shallowly immutable — mutable fields inside break contract. Common mistakes: Adding mutable collections without defensive copy in compact constructor. Best practices: Use compact constructor to validate; combine sealed + records for domain ADTs. Audience level: Senior.
Full explanation
record Point(int x, int y) generates constructor, equals, hashCode, toString. sealed permits restricts subclasses — exhaustive pattern switch in Java 21+.
Real example & use case
API result type: sealed interface Result permits Success, Failure with record payloads.
Pros & cons
Pros: Less boilerplate; algebraic modeling with compiler-checked exhaustiveness. Cons: Records shallowly immutable — mutable fields inside break contract.
Common mistakes
Adding mutable collections without defensive copy in compact constructor.
Best practices
Use compact constructor to validate; combine sealed + records for domain ADTs.
Follow-up questions
- How would you test Records and Sealed Classes?
- What metrics prove Records and Sealed Classes is healthy in prod?
- How does Records and Sealed Classes change at 10× traffic?