Search⌘ K
AI Features

Sealed Classes

Explore how sealed classes improve object-oriented design by limiting inheritance to a defined set of subclasses. Understand the use of sealed, final, and non-sealed modifiers, how to enforce type safety, and how sealing enhances polymorphism with compiler-verified exhaustive switch statements.

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 ...