Why this matters
- Before sealed types, a public interface could be implemented by anyone, so every
switchover its subtypes needed a defensivedefaultthat 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
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
Any other type that tries to implement Shape fails to compile — the hierarchy cannot be extended from outside.
Now the compiler knows there are exactly three shapes, and it can prove a switch is complete.
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.