Skip to main content
PreparationZone Logo
PrepZone

Sealed Classes

Closing a hierarchy on purpose, so the compiler can prove you handled every case.

Pass checkpoint below

Why this matters

  • Before sealed types, a public interface could be implemented by anyone, so every switch over its subtypes needed a defensive default that silently swallowed new cases.
  • Sealing plus records plus pattern matching is the combination behind data-oriented programming in modern Java, and the three features were designed together.
  • It makes a design decision explicit in the code: this hierarchy is a closed set of alternatives, not an extension point.

The problem

Java
Loading compiler…

A new Triangle compiles fine everywhere and fails at runtime, possibly months later. The compiler cannot help, because it has no idea how many shapes exist.

Sealing the hierarchy

Java
Loading compiler…
sealed interface Shapepermits Circle, Square, Triangle
Circlerecord
Squarerecord
Trianglerecord

Any other type that tries to implement Shape fails to compile — the hierarchy cannot be extended from outside.

Because the permit list is closed, the compiler knows every possible case. That is what lets a switch over a sealed type drop the default branch safely.

Now the compiler knows there are exactly three shapes, and it can prove a switch is complete.

Java
Loading compiler…

Add a fourth shape to the permits clause and this method stops compiling until you handle it. Every switch over Shape across the whole codebase does the same. That is the entire point.

The rest of this guide is part of Pro

Free covers every fresher guide in full. Pro unlocks Senior, Staff and Architect guides across every track.

Still to come · 5 sections

  • The rules
  • Sealed versus the alternatives
  • A realistic use
  • What it looks like at runtime
  • Common misreadings

Test yourself

Answer these before moving on — recall is what makes it stick.