A class or interface can declare exactly which types may extend or implement it, making the hierarchy closed and known to the compiler.
The problem it solved
A public abstract type could be extended by anyone, so no switch over its subtypes could ever be proven complete and no invariant across the hierarchy could be guaranteed.
How you did it before
Package-private constructors plus documentation, or an enum when the cases carried no data. Neither gave the compiler anything to check.
Journey: Preview in 15 (JEP 360) and 16, final in 17.
Asked as
- What do sealed classes enable that abstract classes cannot?
- How do sealed types, records and pattern matching work together?
- Why must a sealed type's permitted subclasses be in the same module or package?
Scenario question
You are modelling the result of an operation as either a success with a value or one of three specific failures, and every call site must handle all four.
How do you model it so a missed case cannot compile?
What a good answer weighs
A sealed interface with four record implementations, switched over with patterns and no default branch. The compiler then enforces exhaustiveness. Compare honestly with the alternatives — an enum plus a nullable payload, or exceptions — and say why algebraic modelling beats both when the cases carry different data.