Sealed class
- Java course
- Intermediate
- Lesson 57/116
- 5 min
Learn restricted inheritance with sealed classes.
What is a sealed class?
A sealed class explicitly lists which classes may inherit from it. It is defined with the sealed keyword; allowed subclasses are specified with permits. It became standard in Java 17.
Example: sealed class Shape permits Circle, Square { }. Here Shape allows only Circle and Square to inherit. Another class cannot write extends Shape; it gets a compile error. This keeps the hierarchy predictable. Subclasses must be final, sealed or non-sealed. Sealed is the official way to close the inheritance tree. It is powerful together with pattern matching.
The advantage of sealed
Sealed classes make code predictable by restricting the inheritance hierarchy. Because the compiler knows all subclasses, it can do exhaustiveness checks in features like pattern matching.
Example: if you define sealed class Shape permits Circle, Square, then in a switch covering the Circle and Square cases the compiler verifies all options are handled. This catches missing cases early. Without sealed, who extends Shape cannot be known; the check is impossible. Sealed also helps library designers protect the hierarchy. The subclass list stays stable across versions.
Practice Define the sealed Shape class
Define sealed class Shape permits Circle, Square { }. Then write final class Circle extends Shape { } and final class Square extends Shape { }. In main define a Shape array: Shape[] shapes = { new Circle(), new Square() };. Loop with for and print each one's class name with System.out.println(s.getClass().getSimpleName());.
Starter code
// Define the sealed Shape class
// Write Circle and Square subclasses as final
// In main build a shapes array and print in a loopSample solution
sealed class Shape permits Circle, Square {
}
final class Circle extends Shape {
}
final class Square extends Shape {
}
class Main {
public static void main(String[] args) {
Shape[] shapes = { new Circle(), new Square() };
for (Shape s : shapes) {
System.out.println(s.getClass().getSimpleName());
}
}
}Expected output
Circle Square
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which keyword lists subclasses in a sealed class?
- extends
- implements
- permits Correct answer
- with
Explanation: The permits keyword lists subclasses.
2 Match the sealed class concepts
| Term | Meaning |
|---|---|
sealed |
Restricted inheritance keyword |
permits |
Permission list keyword |
final |
Closed subclass |
non-sealed |
Open subclass |
3 Complete the permits line
sealed class Shape ____ Circle, Square { }
final class Circle extends Shape { }
final class Square extends Shape { }
sealed class Shape permits Circle, Square { }
final class Circle extends Shape { }
final class Square extends Shape { }
Explanation: The permits keyword lists allowed subclasses.