Java sealed classes

Updated:

Java 15 introduced the sealed classes as Preview feature.

Sealed classes allow you to limit the extensibility of one class to a predefined set of subclasses.

Before the sealed classes it was possible to limit the extensibility of a class to the package level, this had the drawback of limiting the accessibility and use of this class from outside the package.

Why sealed classes?

According to the official JEP 360:

Sealed classes and interfaces restrict which other classes or interfaces may extend or implement them.

... it should be possible for a superclass to be widely accessible (since it represents an important abstraction for users) but not widely extensible (since its subclasses should be restricted to those known to the author).

The documentation of Oracle is pretty good, you can find it here:
Java SE Language Updates - Sealed classes

For a deep dive you can read this document of Brian Goetz:
Data Classes and Sealed Types for Java

Because of the extensive documentation we will limit this post to a basic example that can give an idea of the new feature.

Example

sealed class Person permits Man, Woman, Child { 
    public String name; 
} 
non-sealed class Man extends Person {} 
final class Woman extends Person {} 
 
sealed class Child extends Person permits Boy, Girl {} 
final class Boy extends Child {} 
final class Girl extends Child {} 
class Superman extends Man {}; 
// final class Sun extends Person {}; // =>  Alient is not allowed in the sealed hierarchy 

This code is can be represented by the following schema:

Feature of Java 17 LTS

The sealed class Person can define which other classes are authorized to extend it.
Person permits Man, Woman, Child means that the class Person can be extended only by the classes Man, Woman and Child.

The extended classes need to have one of the following modifiers:

sealed : the class can be extended by the defined classes using permits

non-sealed : any class can extend this class

final : the class cannot be extended


WebApp built by Marco using SpringBoot 3.2.4 and Java 21, in a Server in Switzerland