← Back to Chapters

Sealed Classes

? Sealed Classes

? Quick Overview

Sealed classes are a modern object-oriented feature that restricts which classes are allowed to extend or implement them. They provide stronger control over class hierarchies while keeping code readable, predictable, and secure.

? Key Concepts

  • Restricts inheritance to a fixed set of known subclasses
  • Improves code safety and maintainability
  • Commonly used with pattern matching and switch expressions
  • Introduced in Java 17 (finalized)

? Interactive Simulator

The class below allows only CreditCard and PayPal.
Click a subclass button to see if the compiler accepts it.

public sealed class Payment
permits CreditCard, PayPal
 

? Syntax & Theory

A sealed class explicitly declares which classes are permitted to extend it using the permits keyword. Subclasses must declare themselves as final, sealed, or non-sealed.

? View Code Example
// Sealed base class restricting inheritance
public sealed class Shape permits Circle, Rectangle {
}
? View Code Example
// Allowed subclass marked as final
public final class Circle extends Shape {
}
? View Code Example
// Another permitted subclass
public final class Rectangle extends Shape {
}

? Explanation

The Shape class controls its hierarchy by allowing only Circle and Rectangle to extend it. Any other class attempting to inherit from Shape will cause a compile-time error.

✅ Tips & Best Practices

  • Use sealed classes when the domain model is fixed
  • Combine with pattern matching for safer switch logic
  • Prefer sealed classes over enums for complex hierarchies

? Try It Yourself

  • Create a sealed class Vehicle with permitted subclasses
  • Experiment with non-sealed subclasses
  • Try using sealed classes inside a switch expression