Sealed Classes in Java

Abdelbaki BEN ELHAJ SLIMENE
6 min readAug 7, 2023

Sealed classes, a new addition to the Java programming language starting from Java 15, provide developers with a powerful tool for defining restricted class hierarchies. By explicitly specifying which classes can extend or implement them, sealed classes offer enhanced control over inheritance and extensibility.

Photo by Jeremy Bishop on Unsplash

This article explores the concept of sealed classes in Java, their syntax and declaration, as well as their purpose, benefits, and limitations.

What are Sealed Classes?

Sealed classes in Java are a new feature introduced in Java 15 that allows developers to restrict the inheritance hierarchy of a class. By marking a class as sealed, you can control which other classes can extend it. This adds an extra layer of control and encapsulation to your code.

Sealed classes have evolved from sealed interfaces, which were introduced in Java 15 as well. Sealed interfaces restrict the implementation to a limited set of classes. With the introduction of sealed classes, the same concept of restriction has been extended to class inheritance, providing a more comprehensive way of managing the hierarchy of classes.

Syntax and Declaration of Sealed Classes

Declaring a Sealed Class

--

--