Java / Java 21 Coding Standards Interview Questions
Explain the internal working of sealed class exhaustiveness checking by the compiler?
When a switch matches on a type declared sealed, the compiler reads that type's permits clause to obtain the complete, closed list of allowed subtypes - information it cannot get from an open class or interface, which could be extended by any code anywhere.
flowchart TD
A[Compile switch over sealed type T] --> B[Read T permits clause]
B --> C[Build required set of subtypes]
C --> D{Does every case in the switch cover one subtype?}
D -->|yes, all covered| E[Switch is exhaustive, compiles without default]
D -->|no, one or more missing| F[Compile error: switch is not exhaustive]
The compiler then cross-checks the cases actually written in the switch against that required set; if every permitted subtype has a corresponding case (directly, or via a record pattern that deconstructs it), the switch is considered exhaustive and compiles without needing a default branch at all.
If a new subtype is later added to the permits clause, every existing switch over that sealed type that lacks a matching case immediately fails to compile, which is precisely the safety guarantee coding standards rely on when recommending sealed hierarchies over open ones for closed domains.
More Related questions...