Sealed classes ensure switch expressions are exhaustive by design.
Sealed classes in Java allow you to define a fixed set of subclasses. When a switch expression involves a sealed class, the compiler can check if all possible subclasses are covered. This prevents runtime errors due to unhandled cases. For instance, in a payment processing system, if 'PaymentMethod' is a sealed class with known subclasses like 'CreditCard', 'PayPal', and 'BankTransfer', the switch expression must handle all these types. Adding a new subclass will result in a compile-time error if not accounted for, thus enforcing completeness.
Additional Notes
Why does sealed classes on exhaustiveness checking in switch expressions matter in practice?