SEALED CLASSES AND SEALED INTERFACES IN JAVA

java-logo

This brings us to the important question what is a sealed class? Let’s take a step back.

Tipi di classi

We are in the condition where a class can be completely inherited, or if declared as final it cannot be inherited at all. The sealed classes fall between these two extremes by posing alternative solutions to us. Let’s look at the definition.

definizione

With the sealed keyword the class becomes sealed however the permits keyword allows us to specify a list of classes that can inherit it.

Sottoclassi

However, even doing so we get the following compiler error.

Errore

This error specifies that subclasses must specify one of the three modifiers given in the error message. Let us introduce the most common situation.

final

By final we denote the last point of inheritance beyond which we cannot descend, in effect declaring the end of the hierarchy. Let’s look at the second possibility.

sealed

CClass is the last class in the hierarchy and cannot be inherited (modifier final). Let’s look at the third possibility.

non-sealed

With the non-sealed modifier we have broken the seal, i.e., BClass goes back to being free to be inherited by any other class.

LE SEALED INTERFACE

It continues along the same lines as the sealed classes applied, however, to interfaces.

Let’s look at the figure.

sealed interface

As well as classes you can specify final, sealed and non-sealed modifiers.

Ereditarietà tra interface

Let’s look at the last example.

Ereditarietà e implementazione

LINKS TO PREVIOUS POSTS

THE JAVA LANGUAGE

LINK TO CODE ON GITHUB

GITHUB

EXECUTION OF THE EXAMPLE CODE

  • Download the code from GITHUB, launch the JAR file with the following command in Visual Studio Code, locating in the directory containing the JAR.

         java -jar –enable-preview CorsoJava.jar

  • Or run the main found in the file CorsoJava.java.