Sitemap
Syed Nazeer

Syed Nazeer

I'm a Java enthusiast, developing passion for technical content creation.

Sealed Classes

3 min readJun 2, 2026

--

Sealed Classes in Java (Java 17 → 21) — structured, practical, and with real-world insights.

1. What are Sealed Classes?

Sealed classes restrict which classes can extend or implement them.

sealed class Shape permits Circle, Rectangle, Square {}

Only Circle, Rectangle, Square can extend Shape.

2. Why Sealed Classes?

Problem (Before Java 17)

  • Anyone could extend your class → uncontrolled inheritance
  • Hard to enforce domain constraints
  • Pattern matching not safe (no exhaustiveness)

Solution

Sealed classes give:

  • Controlled hierarchy
  • Better domain modeling
  • Compiler guarantees
  • Perfect fit with pattern matching

3. Types of Sealed Hierarchy

Every permitted subclass must declare ONE of these:

1. final

final class Circle extends Shape {}

➡ No further inheritance

2. sealed

sealed class Rectangle extends Shape permits FilledRectangle {}

➡ Further restricted hierarchy

3. non-sealed

non-sealed class Square extends Shape {}

➡ Open for extension again

4. Rules (IMPORTANT for interviews)

→A sealed class must specify permits
→All permitted classes must:

  • Be in same package (or same module)
  • Extend the sealed class directly
    →Subclasses must declare final/sealed/non-sealed

5. Full Example

sealed interface Shape permits Circle, Rectangle, Triangle {}

record Circle(double radius) implements Shape {}

record Rectangle(double length, double width) implements Shape {}

final class Triangle implements Shape {
double base, height;
}

6. Best Feature: Works with Pattern Matching

Exhaustive Switch (NO default needed)

public static double area(Shape shape) {
return switch (shape) {
case Circle c -> Math.PI * c.radius() * c.radius();
case Rectangle r -> r.length() * r.width();
case Triangle t -> 0.5 * t.base * t.height;
};
}

Compiler checks:

  • All types covered
  • No missing cases

7. Sealed Interfaces vs Sealed Classes

Feature Sealed Class Sealed Interface

Inheritance single multiple

Use case base class domain contracts

Preferred for behavior + fields abstraction

Get Syed Nazeer’s stories in your inbox

Join Medium for free to get updates from this writer.

In modern Java: Prefer sealed interfaces + records

8. Real-World Use Cases

1. Domain Models

sealed interface OrderStatus permits Created, Shipped, Delivered, Cancelled {}

2. API Responses

sealed interface ApiResponse permits Success, Error {}

3. Payment Systems (classic)

sealed interface Payment permits Card, UPI, Cash {}

4. State Machines

  • Order lifecycle
  • Workflow engines
  • Finite states

9. Sealed vs Enum (VERY IMPORTANT)

Press enter or click to view image in full size

Example Difference

❌ Enum:

enum Status {
SUCCESS, ERROR
}

✅ Sealed:

sealed interface Response permits Success, Error {}
record Success(String data) implements Response {}
record Error(String message) implements Response {}

10. Sealed vs Abstract Class

Press enter or click to view image in full size

11. Integration with Records (Best Practice)

Most modern design:

sealed interface Event permits UserCreated, UserDeleted {}
record UserCreated(String name) implements Event {}
record UserDeleted(String id) implements Event {}

→ Immutable
→ Thread-safe
→ Clean DTO modeling

12. With Guards (Advanced pattern matching)

return switch (shape) {
case Circle c && c.radius() > 10 -> "Large Circle";
case Circle c -> "Small Circle";
case Rectangle r -> "Rectangle";
case Triangle t -> "Triangle";
};

13. When NOT to Use

→ When extension must be open
→ Framework-based inheritance (Spring proxies)
→ Plugin systems (unknown subclasses)

14. Performance Impact

  • No runtime overhead
  • Purely compile-time safety feature
  • Works efficiently with switch bytecode

15. Version Timeline

Press enter or click to view image in full size

16. Interview One-Liner

“Sealed classes restrict inheritance and enable exhaustive, type-safe pattern matching, making them ideal for modeling closed domain hierarchies.”

17. Common Interview Questions

Q1: Why sealed classes?

➡ To control inheritance + enable exhaustive pattern matching

Q2: Difference from enum?

➡ Sealed supports state + behavior + hierarchy

Q3: Why no default in switch?

➡ Compiler knows all subclasses

Q4: Can sealed be extended outside package?

➡ No (unless using modules with exports)

18. Best Practices (VERY IMPORTANT)

✔ Prefer sealed interface + records
✔ Keep hierarchy small and meaningful
✔ Use with switch expressions
✔ Combine with pattern matching
✔ Avoid unnecessary deep hierarchies

Final Takeaway

Sealed classes = Controlled OOP + Functional style branching

They shine when combined with:

  • Records
  • Pattern matching
  • Switch expressions

--

--

Written by Syed Nazeer

I'm a Java enthusiast, developing passion for technical content creation.