Command Palette

Search for a command to run...

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

final, sealed and non-sealed children

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?

final, sealed and non-sealed children Java 17+
Sign in to run this example in your browser.

Expected output

Car has 4 wheels
Truck has 6 wheels
HeavyTruck has 18 wheels
Bike has 2 wheels
EBike has 2 wheels
Vehicle: sealed
Car: final
Truck: sealed
Bike: open