Java Sealed Classes Cheat Sheet
Syntax for sealed, non-sealed, and final permitted subclasses, plus exhaustive pattern matching with switch, as finalized in modern Java.
1 PageIntermediateFeb 8, 2026
Declaring a Sealed Hierarchy
sealed restricts which classes/interfaces may extend or implement it.
java
public sealed interface Shape permits Circle, Square, Rectangle {}public final class Circle implements Shape { public final double radius; public Circle(double radius) { this.radius = radius; }}public final class Square implements Shape { public final double side; public Square(double side) { this.side = side; }}// Permitted subclasses must be final, sealed, or non-sealedpublic non-sealed class Rectangle implements Shape { public double width, height;}
Same-File / Same-Module Shortcut
permits is optional when all subclasses are in the same file.
java
// If all permitted subtypes live in the same source file, permits can be omittedsealed interface Result<T> { record Ok<T>(T value) implements Result<T> {} record Err<T>(String message) implements Result<T> {}}
Exhaustive Pattern Matching
The compiler verifies switch covers every permitted subtype — no default needed.
java
static double area(Shape shape) { return switch (shape) { case Circle c -> Math.PI * c.radius * c.radius; case Square s -> s.side * s.side; case Rectangle r -> r.width * r.height; // no default clause required: compiler proves exhaustiveness };}// With record patterns (deconstruction)static String describe(Result<Integer> result) { return switch (result) { case Result.Ok<Integer> ok -> "value: " + ok.value(); case Result.Err<Integer> err -> "error: " + err.message(); };}
Permitted-Subclass Modifiers
Every direct subclass of a sealed type must pick exactly one.
- final- no further subclassing allowed
- sealed- continues the restriction with its own permits list
- non-sealed- reopens the hierarchy, any class may extend it
- permits- explicit list of allowed direct subtypes (optional if same file)
- record- records are implicitly final, so they satisfy the sealed contract directly
Pro Tip
Combine sealed hierarchies with exhaustive switch expressions to get compile-time enforcement that every case is handled — adding a new permitted subtype breaks the build everywhere a switch forgot to handle it, which is exactly what you want.
Was this cheat sheet helpful?
Explore Topics
#JavaSealedClasses#JavaSealedClassesCheatSheet#Programming#Intermediate#DeclaringASealedHierarchy#Same#File#Module#OOP#CheatSheet#SkillVeris
Advertisement
Sri Hayavadhana Info-Tech
Professional Web Designing Services
- Responsive Websites
- E-commerce Solutions
- SEO Friendly Design
- Fast & Secure
- Support & Maintenance