×

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;  
}  
}   

Related Topics

Character Array in Java

A character array is an array which holds values of character data types. It is different from a string array. The character array, string, and StringBuffer classes in the Java...

4 minutes read.

Producer Consumer Problem in Java Using Synchronized Block

The producer-consumer dilemma is a well-known instance of a multi-process synchronization issue in computing. Two processes—the producer and the consumer—are described in the issue, and they share a single, fixed-size...

4 minutes read.

Java Extends vs Implements

Java: We known that the java is a pure object oriented programming language. Java programming language consists of many features such as portable, plat form independence, secured, robust, simple, architecture neutral,...

4 minutes read.

Tetris Game in Java

The Tetris game is among the most well-known video games ever produced for computers. Today, we may engage in this game on a mobile device as well. Alexey Pajitnov conceptualized...

12 minutes read.

Stack Program in Java

Stack Program in Java The Stack class is part of the collection framework that inherits the Vector class. Thus, the Stack class can also be called a subclass of the Vector...

5 minutes read.

Java String length() method

Java String length() method returns length of the characters in a String. Syntax: public int length() Returns It returns length of the characters Java String length() method example 1          public class JavaStringLengthEx1  ...

1 minute read.

Java Program to generate binary numbers

A binary tree can create binary numbers ranging from 1 to n. Every node in a tree, the right, and left nodes, has two children, as is common knowledge. The...

3 minutes read.

Java Interface Keyword

An interface is also known as the blueprint in Java. It has constants of static values and methods of abstraction. The interface is a mechanism used by Java to declare...

3 minutes read.

Map of Map in Java

The map is now a Java interface for mapping keys to values. It is frequently necessary to use Map of Map (nested Map). Nested Maps are useful in various situations, including...

3 minutes read.

Java Program to remove duplicate characters in a string

In strings, we can find many characters present one or more times in a string; accessing a particular character is difficult due to repetition. Duplicate characters will present in the...

5 minutes read.

Brilliant Number in Java

It is a number N that is made up of two prime numbers that have the same number of digits and is called a brilliant number. Several/Some of the brilliant Numbers...

3 minutes read.

How to Calculate the Time Difference between Two Dates in Java?

The date is used extensively in Java to calculate date discrepancies. The date of joining an organization, admittance, appointment, etc., can be included when creating the application. The differences between...

4 minutes read.

How to Convert String to enum in Java?

In this article, we shall gain the complete knowledge about how to convert the string to enum in Java. The complete process that happens in the approach shall be discussed...

3 minutes read.

Java Hello World

Let’s start by writing a simple program that prints “Hello World” to the output window. Write the program into any text editor or IDE (Eclipse, Netbeans, etc.) and save the file with the...

2 minutes read.

How to Convert int to long in Java

How to Convert int to long in Java When two variables of different types are involved in the single expression, Java compiler uses built-in library function to convert the variable to...

2 minutes read.

Package Program in Java

Package Program in Java The package program in Java helps us to understand the significance of packages in Java. Packages are mainly used to group together similar classes, interfaces and sub-packages....

6 minutes read.

MVC in Java

A well-known design pattern is Model-View-Controller. The discipline of web development. We can organize our code in this manner. The document stipulates that a program or application must include a...

4 minutes read.

Class vs Object in Java

Java : Java is a pure object oriented language. It was introduced by James Gosling in the year 1995. The first public implementation of java was done by sun micro systems...

7 minutes read.

Empty Statement in Java

The three sorts of statements in Java are control, expression, and declaration statements. Additionally, another statement is referred to as an empty statement. In this section, we will discuss about...

4 minutes read.

Java Integer rotateLeft() method

The rotateLeft() method of Java Integer class returns the value obtained by rotating the  2’s complement binary representation of the given integer value left by the specified number of bits. Syntax public...

1 minute read.