Java / Java 21 Coding Standards Interview Questions
How does the compiler enforce exhaustiveness in a switch over sealed types?
Exhaustiveness enforcement is a two-part compile-time check: first, the compiler resolves the full, closed set of permitted subtypes from the sealed type's declaration; second, it verifies that the switch's cases, taken together, cover every member of that set with no gaps.
sealed interface Shape permits Circle, Square {} // missing a Square case below is a compile error, with no default needed return switch (shape) { case Circle c -> c.radius() * c.radius() * Math.PI; };
A subtype that is itself an abstract sealed or non-sealed type is handled recursively: the compiler expands it into its own permitted subtypes and requires those to be covered instead, so a multi-level sealed hierarchy is checked all the way down to its concrete leaf types.
If the cases do not fully cover the set, the compiler reports the specific missing subtype in the error message rather than a generic "non-exhaustive switch" complaint, which is what lets a developer fix the gap immediately instead of hunting for which case was left out.
More Related questions...