11

Java sealed classes - Quick intro

 3 years ago
source link: https://marco.dev/java-sealed-classes
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Java 15 introduce the sealed classes as Preview feature. Preview means that the feature is still in evaluation and development and is not ready for production.

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:

sealed-classes.gif

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


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK