Sealed Classes and Pattern Matching
Fast recall
Quick revision
Core answer
Whether you understand the compiler-enforced exhaustiveness and how sealed classes complement records for algebraic data types (ADTs).
Thinking sealed classes are just about restricting inheritance for security. The real power is compiler-checked exhaustive pattern matching.
Show how sealed + records + pattern matching replaces the visitor pattern and discuss how this models domain types more safely.
Interview-ready guide
Interview answer
Sealed classes aren't about restricting inheritance — they give the compiler a closed set of subtypes so it can enforce exhaustive switch without a default branch.
Exhaustive switch:
sealed interface Shape permits Circle, Rectangle, Triangle— compiler knows exactly three variants- A
switchhandling all three needs nodefault - Adding
Squareto the permits list makes every unhandledswitchoverShapefail to compile
Sealed + records = algebraic data types:
sealed interface Expr permits Num, Add, Mulwith record implementationsswitch (e) { case Num(var v) -> v; case Add(var l, var r) -> eval(l) + eval(r); }— deconstructs each variant inline- Replaces the visitor pattern with shorter, compiler-verified code
Rules and constraints:
- Each permitted subtype must be
final,sealed, ornon-sealed non-sealedreopens the hierarchy for extension but thenswitchrequires adefaultagain- Permitted types must be in the same module (or same package in non-modular projects)
- Reflection-based proxies (Spring AOP, Hibernate) fail on sealed classes — the proxy is not in the
permitslist
I recommend sealed interfaces with record implementations as the default for any closed type hierarchy.
Sealed Classes and Pattern Matching
Direct Answer
Sealed classes (stable in Java 17) restrict which classes can extend or implement them using the permits clause. Combined with pattern matching for switch (Java 21, stable), sealed hierarchies enable exhaustive switch expressions — the compiler verifies all permitted subtypes are handled, eliminating the need for a default branch and catching missing cases at compile time.
Common Mistakes & Pitfalls
Thinking sealed classes are just about restricting inheritance for security. The real power is compiler-checked exhaustive pattern matching.
Check your understanding
Answer these without looking back at the article.
- How do sealed classes replace the visitor pattern?
- What is the difference between sealed and final?
- How does Kotlin data class + when compare to Java records + sealed switch?
Related interview prep categories
1Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.