Records and Sealed Classes
As a Fresher engineer, explain Records and Sealed Classes. What problem does it solve and how would you describe it in an interview?
Answers use simple, clear English.
Quick interview answer
At Fresher depth: start with the problem, then mechanism, then a short example. record Point(int x, int y) generates constructor, equals, hashCode, toString.
Detailed answer
At Fresher depth: start with the problem, then mechanism, then a short example. record Point(int x, int y) generates constructor, equals, hashCode, toString. sealed permits restricts subclasses — exhaustive pattern switch in Java 21+. 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: Fresher.
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?