×

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

Hourglass problem in Java

In this section, we will discuss the hourglass problem in Java.The aim is to find the largest sum of an hour glass given a 2D matrix. An hour glass is made...

2 minutes read.

Class memory in Java

Anything specifically defined in the Java code is stored either inside the heap or the stack, which is particularly significant. Stack and heap are the two kinds of memory available...

6 minutes read.

How to Send SMS in Java with Example

Sending SMS messages in Java is a fairly common task, and there are a number of libraries and APIs available to help you do it. One popular option is to...

2 minutes read.

Contextual keywords in Java

Contextual keywords were earlier known as restricted identifiers and restricted keywords. Context keywords are chosen based on their expected placement in the syntactic grammar. These are the keywords in the code...

3 minutes read.

Calculator Program in Java

Calculator Program in Java A calculator performs the basic mathematical operations such as addition, subtraction, multiplication, etc. In this section, we will create a calculator program in Java using switch case...

5 minutes read.

Java StringReader Class

StreamReader Class technique enables character reading from a string. The java.io package contains this class. A string serves as a source in the character stream. While the Stream class is...

4 minutes read.

All the important string methods in Java

What is a String? Strings are a bundle of different characters that are normally used in Java programming language. Strings are regarded as objects in the Java programming language. “String” is a...

4 minutes read.

Missing Number in an Arithmetic Progression in Java

Given an array that shows the elements of an orderly arithmetic progression. Find the missing number to complete the succession of elements. Example:  Input: a [ ] = {2 , 4 , 6...

3 minutes read.

Object class in Java

In Java, a class is a file containing the Java byte code. It can essentially specifically be executed on the JVM (Java Virtual Machine), fairly significant. The JVM mostly generally...

6 minutes read.

Java Polymorphism

The process of representing one form in multiple forms is known as Polymorphism. Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly" means many and "morphs" means forms. So polymorphism means...

5 minutes read.

Example of Static import in Java

Static keyword Java's static keyword is mainly used to control memory. Variables, methods, blocks, and nested classes are compatible with the static keyword. Instead of an instance, the static keyword is...

3 minutes read.

String isnullorempty in Java

What do you mean by String? Strings are a collection of characters that are commonly used in Java programming. Strings are regarded as objects in the Java programming language. “String” is a...

4 minutes read.

How to add 4 Hours to the Current Date in Java?

In this tutorial, we will learn how to add 4 hours to the local or current date in Java language. We will begin our topic with basic concepts and would...

2 minutes read.

Java Vs C++

Java Vs C++ Java and C++ both are Object Oriented Programming languages. Both languages are popular for competitive programming. C++ is used by many coders who have just started learning programming...

4 minutes read.

Java Command not found

Java Command not found error is displayed if Java is not installed on the computer or if the command prompt cannot find Java.exe to run the program. Our Java software...

3 minutes read.

Creation of Multi Thread in java

What are threads in Java? We can use threads to facilitate parallel processing. Threads are helpful when you wish to execute several pieces of code concurrently. A thread is a small process...

3 minutes read.

Java Return Keyword

The return keyword in Java is used to end a method's execution. the caller receives the return, followed by the appropriate value. The return type of the method, such as...

3 minutes read.

Lazy loading in Java

Lazy loading is the idea of waiting to load an object until you need it. In other words, it is the practice of postponing class instantiation until it is necessary....

5 minutes read.

Abstract classes in Java

Abstract classes in Java Java uses the 'abstract’ keyword to make a class abstract. Such classes are known as abstract classes, and the process is known as abstraction. In programming language, abstract...

4 minutes read.

How to check Date is Greater in Java?

In this article, you will be acknowledged about how to check if the given date is greater than the other date or not. We are simply comparing the dates and...

7 minutes read.