Command Palette

Search for a command to run...

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

A sealed shape family (Java 17 style)

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?

A sealed shape family (Java 17 style) Java 17+
Sign in to run this example in your browser.

Expected output

Circle[r=1.0] -> 3.14
Square[side=2.0] -> 4.00
Rectangle[w=2.0, h=5.0] -> 10.00
Shape is sealed: true
  permits Circle
  permits Square
  permits Rectangle