Exhaustive switch over a sealed type
Needs Java 21. Add a fourth record to the permits list and both switches stop compiling until you handle it.
A sealed class or interface lists exactly which classes may extend or implement it, with permits. The family is closed: the compiler and JVM reject any other subclass, and (from Java 21) a switch over a sealed type can be checked for completeness without a default.
Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Model sealed interface Expr permits Num, Add, Mul with records, and write a Java 17-compatible eval(Expr) using instanceof patterns. Evaluate (2 + 3) * 4.
Model traffic-light states as a sealed interface with three records, and write next(Light) that cycles Red → Green → Amber → Red. Print four steps from Red.
Write a sealed class Account with final subclasses Savings and Current, then print Account.class.getPermittedSubclasses() names.
Explain it without notes
What do sealed, permits, final and non-sealed each do?
Where must permitted subclasses live?
How do sealed types make switch statements safer?
How is sealing enforced at run time?
Expected output
Card ending 4242: 2500.0 | fee 50.0
Card ending 1111: 300.0 | fee 5.0
UPI asha@bank: 800.0 | fee 0.0
Cash: 150.0 | fee 0.0