SEALED CLASSES AND SEALED INTERFACES IN JAVA
This brings us to the important question what is a sealed class? Let’s take a step back.
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.
With the sealed keyword the class becomes sealed however the permits keyword allows us to specify a list of classes that can inherit it.
However, even doing so we get the following compiler error.
This error specifies that subclasses must specify one of the three modifiers given in the error message. Let us introduce the most common situation.
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.
CClass is the last class in the hierarchy and cannot be inherited (modifier final). Let’s look at the third possibility.
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.
As well as classes you can specify final, sealed and non-sealed modifiers.
Let’s look at the last example.
LINKS TO PREVIOUS POSTS
LINK TO CODE ON 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.
Leave A Comment