Sealed class — a class that restricts which other classes or interfaces may extend or implement it, providing explicit control over the class hierarchy.
1public sealed class Shape permits Circle, Rectangle, Triangle {}23public final class Circle extends Shape {4 private final double radius;5 public Circle(double radius) { this.radius = radius; }6 public double area() { return Math.PI * radius * radius; }7}89public non-sealed class Rectangle extends Shape {10 private final double width, height;11 public Rectangle(double w, double h) { this.width = w; this.height = h; }12 public double area() { return width * height; }13}1415public sealed class Triangle extends Shape permits IsoscelesTriangle {16 // Triangle is sealed — only IsoscelesTriangle can extend it17}1819public final class IsoscelesTriangle extends Triangle {}
Permitted Modifiers for Subclasses:
Benefits:
Pattern Matching with Sealed Classes:
1// Compiler knows ALL subtypes of Shape2public static String describe(Shape shape) {3 return switch (shape) {4 case Circle c -> "Circle with radius " + c.radius();5 case Rectangle r -> "Rectangle " + r.width() + "x" + r.height();6 case Triangle t -> "Triangle";7 // No default needed — compiler verifies exhaustiveness8 };9}
Key Points:
Common Pitfalls: