Search⌘ K
AI Features

Sealed Classes

Explore how sealed classes in Java let you control which classes can extend a given parent, ensuring predictable and secure class hierarchies. Understand how to define sealed classes with permits, apply final, sealed, or non-sealed modifiers to subclasses, and leverage sealed interfaces. Discover how this feature supports safer polymorphism and enables the compiler to verify exhaustive handling in switch expressions.

Inheritance allows us to extend functionality, and abstract classes let us define incomplete templates. However, traditional inheritance in Java is open by default. Any class, anywhere, can extend a non-final public class. While this flexibility is useful, it creates problems when we want to model a specific, finite set of possibilities.

For example, if we are building a graphics system, a Shape might only ever be a Circle, Square, or Triangle. If we leave the class open, a developer could unexpectedly add a Hexagon years later, potentially breaking logic that assumed only three shapes existed.

Sealed classes allow us to restrict inheritance to a specific set of trusted subclasses, giving us total control over our class hierarchy.

Defining a sealed class

To restrict inheritance, we use the sealed modifier on a class declaration. When we seal a class, we must explicitly tell the compiler which classes are ...