Sealed Class in Java
What is a Sealed Class in Java?
In programming, the two main issues that must be taken into account when creating an application are security and control flow. The use of final as well as protected keywords, among other regulating characteristics, limits the user's access to variables and methods. In Java 15, a unique preview feature enables us to manage an inheritance.
Purpose of Sealed Class in Java
Java SE 17's introduction of sealed methods (JEP 409).
The purpose of this feature is to make Java's inheritance control more precise. Classes and interfaces can specify the subtypes that are allowed by using sealing.
In other terms, a class or interface can now specify which classes can extend or implement it. It is a helpful feature for domain modeling and boosting library security.
We can reuse code by using a class structure and inheritance. The class hierarchy may serve additional functions, though. Although code reuse is important, it is rarely our main objective.
Sealed Java Class
Sealing classes was a notion introduced in Java 15. It is a feature for previews. Java-sealed methods and interfaces limit who can extend or implement such classes and interfaces.In other words, the sealed class is the kind of class that can be instantiated but cannot be inherited. It gives classes and interfaces additional control over the subtypes that are allowed within them. It helps create a more secure environment for libraries as well as general domain modeling.
The idea of sealed classes should be understood as a preview feature rather than a permanent one.
Preview Features
a feature that has been fully designed, implemented, and specified but is not permanent. The feature can be present or absent entirely in the next Java SE editions.
Also, take note that it is difficult to build and run code that has a preview feature. Additional command-line arguments are necessary.
Implementing Preview Features
When utilizing the preview feature in a Java application, the compiler and runtime systems must both have the preview capability explicitly enabled. The error message "preview functionality is deactivated by default" appears if we do not activate the preview feature.
To create a Java application with the preview functionality, use the command line:
javac - -enable -preview - -release n programname.java
Or
javac - -enable -preview -programname.java n
where JDK version n is.
Assume we wish to compile and run Demo.java, a source file with preview functionality.
javac --enable-preview --release 12 Demo.java
The based increasing message appears on the console when we generate the source file mentioned above.
Demo.java uses preview language features.
Recompile with -Xlint: preview to get more information.
To launch a Java program with the preview functionality, enter the command line:
java --enable-preview Demo
Note: Compiling or running code that utilizes a preview capability of previous versions of Java SE is not required.
Key Features of Java Sealed Class
In Java 15, sealed classes are introduced as a preview feature, offering fine-grained control over the inheritance. Minor improvements are made by Java 16 and this functionality is still in the preview stage. The important things to think about in a sealed class are as follows:
- The sealed keyword is used to declare sealed classes.
- Using the permitskeyword, sealed classes enable you to specify which classes can be subtypes.
- A class must be designated as sealed, non-sealed, or final before it can extend to another sealed class.
- In inheritance, the use of sealed classes facilitates the creation of a definite and bounded hierarchy of classes.
Making a Class Definable
A sealed class declaration is not overly difficult. The sealed modifier should be added to the declaration of a class if we intend to declare it to be sealed. Add the permits clause after the class declaration extends, and implements clauses. The classes that could expand the sealed class are indicated by the clause.
The following clauses and modifiers are presented:
- sealed: It could only be expanded by the subclasses it is allowed to extend.
- Non-sealed: It can be expanded by unauthorized subclasses; a sealed class never restricts the actions of its authorized subclasses.
- Permits:It permits the subclass to extend and inherit.
- final: Because it forbids future extensions, the allowed subclass must be final.
Sealed Classes
We can seal classes using the same sealed modification as we did for interfaces. Any extended or implemented clauses should come after the permits clause, as follows:
public abstract sealed class Vehicle permits Car, Truck {
protected final String registrationNumber;
public Vehicle(String registrationNumber) {
this.registrationNumber = registrationNumber;
}
public String getRegistrationNumber() {
return registrationNumber;
}
}
A modifier must be defined by a valid subclass. To prevent any additional extensions, it may be deemed to be final:
public final class Truck extends Vehicle implements Service {
private final int loadCapacity;
public Truck(int loadCapacity, String registrationNumber) {
super(registrationNumber);
this.loadCapacity = loadCapacity;
}
public int getLoadCapacity() {
return loadCapacity;
}
@Override
public int getMaxServiceIntervalInMonths() {
return 14;
}
}
Constraints of Java Sealed Class
Three significant restrictions are placed on the permissible subclasses of a sealed class:
- The sealed class and authorized subclasses must be members of the same module.
- The sealed class must be expressly extended by each allowed subclass.
- Each allowed subclass shall define one of the following modifiers: final, sealed, or non-sealed.
The Benefits of Interface and Sealed Classes
- It grants authorization to subclasses that have the power to extend the sealed superclass.
- Superclass is now widely accessible; however, it is not widely expandable.
- It enables compilers to impose the system on class users.
- The creator of a superclass has authority over its subclasses. Therefore, they are able to define functions in a more limited manner.
Sealed Class Uses
Sealing courses are beneficial for the following:
- API for Java Reflection
- java Records
- Pattern Recognition
Example Program
public class SealedClassExample
{
public static void main(String args[])
{
Person grandfather = new GrandFather(87, "Albert");
grandfather.name = "Albert";
System.out.println("The age of grandfather is: "+getAge(grandfather));
}
public static int getAge(Person person)
{
if (person instanceof Father)
{
return ((Father) person).getFatherAge();
}
else if (person instanceofGrandFather)
{
return ((GrandFather) person).getGrandFatherAge();
}
return -1;
}
}
abstract sealed class Person permits Father, GrandFather
{
String name;
String getName()
{
return name;
}
}
final class Father extends Person
{
String name;
int age;
Father(int age, String name)
{
this.age = age;
this.name = name;
}
int getFatherAge()
{
return age;
}
}
non-sealed class GrandFather extends Person
{
int age;
GrandFather(int age, String name)
{
this.age = age;
this.name = name;
}
int getGrandFatherAge()
{
return age;
}
}