×

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

Java String trim() method

Java String trim() method returns String after eliminating leading and trailing spaces. Note:- Java String trim() method doesn't trim or omit middle spaces. Syntax: public String trim() Returns: It returns string with omitted leading and...

2 minutes read.

Java Code Optimization

We encounter the idea of optimization while working on any Java application. It is essential that the code we write is not only clear and error-free but also optimized, meaning...

9 minutes read.

Java Session

Session indicates interval of time. A session is a simple  time interval in which servers and client interacts. To maintain the state of the client or user we use technologies...

5 minutes read.

Java Math nextAfter() Method

The nextAfter() method of Math class returns the floating-point value adjacent to the first argument in direction of the second argument. Syntax: public static double nextAfter (double start, double direction)public static float...

2 minutes read.

Java Linters

When it comes to programming, everyone makes mistakes. Errors are bad for developers since they are difficult to handle. But handling as many as possible errors will bring out the...

6 minutes read.

Difference Between Data Hiding and Abstraction in Java

Abstraction: Data Abstraction and Data Hiding ideas are utilised to show the expected data to the end client and conceal the superfluous subtleties, however, for specific purposes like decreasing the framework's...

10 minutes read.

Java String indexOf() method

Java String indexOf() method returns index of a given character or substring present in a String. Methods Description int indexOf(int ch)     It returns index position for the given char value.int indexOf(int ch,...

2 minutes read.

Java Comparable Interface

We implement comparable interface when we need a new logic for determining equality. if two objects are equal, the equals() method returns true and compareTo() method returns 0. The basic...

1 minute read.

Aggregation in Java

Aggregation A "has-a" and "whole/part" connection is the best way to define the aggregate relationship in Java, which exists between two classes. This connection relationship has a higher level of specialisation....

4 minutes read.

Use Of Adapter class in Java

An adapter class in Java enables listener interfaces to be implemented by default. The Delegation Event Model is where the idea of listener interfaces first appeared. It is one of...

3 minutes read.

Concurrent Modification Exception In Java

When an object is attempted to be updated concurrently when it is not allowed, the ConcurrentModificationException arises. This error typically occurs while using Java Collection classes. When another thread is iterating...

5 minutes read.

How to Create an Immutable Class in Java

How to Create an Immutable Class in Java In Java, immutable means something that cannot be change. A class is called an immutable class if its content cannot be changed, once...

3 minutes read.

Operators in Java

There is a good operator environment provided by Java. These operators are divided into four different groups i.e. arithmetic, bitwise, relational, and logical. There are other operators also available to...

7 minutes read.

Java Integer numberOfLeadingZeros() method

The numberOfLeadingZeros()  method of Java Integer class returns the total number of zero bits preceding the highest-order one-bit in the 2’s complement binary representation of the specified int value.  Syntax public static...

1 minute read.

Java Class Methods

Methods called on a class rather than a specific object instance are known as class methods. The static modifier guarantees uniform implementation across all instances of the class. Syntax public class NameOfClass...

3 minutes read.

Abstract Class Program in Java

Abstract Class Program in Java Abstraction is a technique by which a developer hides the implementation details from the user and shows only the functionality.It is not only confined to the...

6 minutes read.

Java callable example

What is callable in Java? Callable is an interface that is present in Java. There are two methods for constructing threads: one is to inherit the Thread class, while the other...

3 minutes read.

Check the presence of Substring in a String in java

In java, the string can be treated as class and datatype. The string contains words and numbers but should be in double-quotes. Example: ” Omsairam” Substring The part of the string is called...

2 minutes read.

Java Comparator Interface

Java comparator interface is used in a situation when we have to sort an object which does not implement Comparable or do sorting in a different way than the Comparable....

1 minute read.

Conditional operator in Java

In Java, there are around eight operators, and among them, three operators are used to evaluate the condition and decide the Result based on the Result of the evaluated condition. Below...

4 minutes read.