Java 17: Sealed classes restrict the hierarchy

A sealed type permits only a fixed set of subclasses, enabling exhaustive handling.

Code
sealed interface Shape permits Circle, Square {}
record Circle(double r) implements Shape {}
record Square(double side) implements Shape {}

Shape s = new Circle(2);
double area = switch (s) {
    case Circle c -> Math.PI * c.r() * c.r();
    case Square sq -> sq.side() * sq.side();
};
System.out.printf("area=%.2f%n", area);
Output
area=12.57
Advertisement

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-07-26