# Java sealed classes and exhaustive pattern matching

> Java sealed classes prevent runtime errors but require recompiling to avoid breaking code.
- Title: Java sealed classes and exhaustive pattern matching | Shortify
- Summary: Java sealed classes prevent runtime errors but require recompiling to avoid breaking code. Sealed classes ensure exhaustive pattern matching at compile time…
- Keywords: java, sealed classes, exhaustive pattern matching, compile time, runtime error, breaking change, seal interface, technology, startups, sealed, classes, exhaustive
- Source: Neilmadden — https://neilmadden.blog/2026/04/24/java-sealed-classes-and-exhaustive-pattern-matching
- Read time: 1 min
- Topics: java, sealed classes, exhaustive pattern matching, compile time, runtime error, breaking change, seal interface, technology, startups
## Java 17 sealed classes
Java 17 introduced sealed classes to explicitly list allowed sub-types of interfaces or base classes.
## Sealed interface example
A sealed interface with records TypeA and TypeB allows switch expressions without default clauses.
## Exhaustiveness checking
Sealed classes enable compile-time error detection for missing switch cases.
## Adding new subtypes
Adding a new subtype to a sealed class breaks consumers without recompiling.
## Runtime exception risk
Separate compilation causes runtime exceptions when new subtypes are added.
## Internal vs public API
Sealed classes are most useful internally where recompiling everything is possible.
## Key takeaway

Sealed classes ensure exhaustive pattern matching at compile time but break when new subtypes are added without recompiling.