What are sealed classes in Java, and what problem do they solve?
A sealed class is a class that says exactly which other classes may extend it. The list of permitted subclasses is written in the class itself, and the compiler checks that nothing else tries to extend it.
The problem that it solves is this. For a long time, if you wanted the compiler to check that your switch statement handled every possible case, you needed an abstract class or an interface, and then anybody could add a new subclass later and quietly break your code. A sealed class closes the set, so the compiler knows the whole family and can check that you handled all of it.
public class Main {
public static void main(String[] args) {
Shape circle = new Circle(2);
Shape square = new Square(3);
System.out.println("the area of the circle : " + circle.area());
System.out.println("the area of the square : " + square.area());
}
}
// The permitted subclasses are listed here.
sealed interface Shape permits Circle, Square {
double area();
}
record Circle(double radius) implements Shape {
public double area() {
return Math.PI * radius * radius;
}
}
record Square(double side) implements Shape {
public double area() {
return side * side;
}
}
So the answer to the question is this. A sealed class or a sealed interface says that the family of subclasses is fixed and known, and the compiler uses that knowledge to check that your code has handled every one of them.
The next question in this topic looks at how that works with the modern switch.