Command Palette

Search for a command to run...

Back to the lesson: Topic 5.11 — Sealed Classes and Interfaces
Core Java · Example 3 of 3 Java 21+

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.

01

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.

02

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.

03

Write a sealed class Account with final subclasses Savings and Current, then print Account.class.getPermittedSubclasses() names.

Explain it without notes

01

What do sealed, permits, final and non-sealed each do?

02

Where must permitted subclasses live?

03

How do sealed types make switch statements safer?

04

How is sealing enforced at run time?

Exhaustive switch over a sealed type Java 21+
This example needs Java 21+. The in-browser compiler is Java 17: install JDK 21 or newer and run it with "java Main.java".

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