J.VII · Java 25 practice question
Consider a design where you define a sealed interface, `Permit`, representing different types of access rights. You want to process these permits using pattern matching in a `switch` expression. Which of the following implementations correctly ensures that all possible permit types are handled, even if new types are added to the sealed hierarchy in the future?
sealed interface Permit permits AdminPermit, GuestPermit, StandardPermit {}
record AdminPermit() implements Permit {}
record GuestPermit() implements Permit {}
record StandardPermit() implements Permit {}
public String processPermit(Permit p) {
return switch (p) {
// ... implementation using pattern matching
};
}
Check answer and explanation
Correct answer: Using a `switch` expression where the compiler automatically guarantees exhaustiveness because all permitted types are explicitly listed in the `sealed` declaration, making a `default` case optional for compile-time safety.
Explanation
Java's sealed classes and interfaces are designed to work seamlessly with pattern matching (`switch` expressions/statements). When all possible implementations are known and listed within the `sealed` declaration, the compiler enforces exhaustive checking. If you list all permitted types in a `switch` expression, the compiler can guarantee that all cases are covered, meaning an explicit `default` case is often unnecessary for correctness, as the compiler verifies the exhaustiveness based on the sealed hierarchy.
Common trap
Option B suggests that forcing a `default` case is necessary. While this handles runtime scenarios outside the known types, the *design intent* of sealed types is to allow the compiler to verify exhaustive handling of known variants, making the explicit `default` case an anti-pattern if the goal is strictly static checking against the sealed contract.
Source: Sealed classes documentation (Checking the specific JEP for Java 25 if available, otherwise general sealed class docs) https://docs.oracle.com/en/java/javase/25/language/sealed-classes.html
Checked against the cited text on 2026-11-27.