A class which is declared as sealed in java. Basically sealed class restricts which class need to be extended and which class don’t. Sealed class cannot be inherited, but it can be instantiated. ‘permits’ is a keyword which allows to restrict subtypes of a sealed class.
Table of Contents
What does really sealed class means?
Literally, When you are developing an application there are mainly two major concerns security and control flows. ‘private’, ‘protected’ and ‘final’ keywords are generally used to restrict the users to access the variables and methods.
From Java 15, sealed, non-sealed and permits keywords are allowed for security purpose in inheritance hierarchy.
Prior to sealed, There was a concept of final class. Final classes can’t be modified i.e it can’t be inherited nor be extended. So, if there is situation that sub class need to be modify then there is no option to do that. So, Concept of sealed class help to those types of conditions.
Sealed class is process to limits the numbers of sub class need to inherited or extended.
Note: All programs have run on Java 21. If you run on different versions, then data may be inconsistent
for eg:
package com.programming.seekho;
public class SealedClassDemo {
public static void main(String[] args) {
A objA = new A();
B objB = new B();
C objC = new C();
objA.print();
objB.print();
objC.print();
}
}
sealed class A permits B,C{
public void print(){
System.out.println("Hi! I'm in A class");
}
}
non-sealed class B extends A{
public void print() {
System.out.println("Hi! I'm in B class");
}
}
final class C extends A{
public void print() {
System.out.println("Hi! I'm in C class");
}
}
Output
Hi! I'm in A class
Hi! I'm in B class
Hi! I'm in C class
In the above program, class A is the super class and B, C are sub class. Class A is declared as sealed which should have at least one sub class so here we have declared 2 sub class B and C. A permits both B, C class that needs to be intantiated.
If super class is sealed then sub class or child class can be non-sealed and final but not sealed. Because if you want to declared sub class as ‘sealed’ then at least one child class should be extend to it.
How to define sealed class and interface?
sealed class D {...}
sealed interface E {…}
Why do we need sealed class in java?
Class hierarchies would be complex when you are developing a large scale application. Lots of classes extending same super class which leads to challenging task to maintain all these classes. The classes which are unintentionally extended or inherited from same super class so it creates some issues or bugs in the application.
So to avoid these issues, sealed class has been introduced in Java. It provides a mechanism to specify which class need to be extend and which class don’t.
Benefits of sealed class
- It controls over subclasses which is bounded by sealed class.
- It reduces the risk of unintentional extensions.
- It enhances code readability due to sealed class indicates which sub class is allowed
- Catching error during compilation time for which sub classes are not permitted.
- ‘permits’ keyword is used to provide permission to sub classes.
- If client want to create unauthorized sub classes. It won’t be possible.
What is non sealed class in java?
Non sealed class is a concrete class. It must extend to super class. Non-sealed keyword always used with sub class or child class not with super class. That means if super class is sealed then sub class should be non sealed or final.
We can create the object of non sealed class so that if any method is overridden then we can call these methods with object. Non sealed class can be permitted by super class
What is the difference between sealed class and abstract class?
Sealed class can be instantiate but abstract class cannot be instantiate. Abstract class is intantiated by its implemented class.
for eg:
package com.programming.seekho;
public class SealedAndAbstractDemo {
public static void main(String[] args) {
Engineer engineer = new Engineer();
engineer.printDepartment();
//Branch branch = new Branch();
BranchCSE cse = new BranchCSE();
cse.print();
}
}
sealed class Engineer{
String dept1 = "Java";
String dept2 = "Desktop";
void printDepartment(){
System.out.println("Department 1 : "+dept1);
System.out.println("Department 2 : "+dept2);
}
}
final class SoftwareEngineer extends Engineer{
}
abstract class Branch{
String stream1 = "CSE";
String stream2 = "Electrical";
void printBranch(){
System.out.println("Branch 1 : "+stream1);
System.out.println("Branch 2 : "+stream2);
}
}
class BranchCSE extends Branch{
void print(){
System.out.println("Branch 1 : "+stream1);
}
}
Can we have constructor in sealed class?
Of course, We can have constructor also in a sealed class. It can be default and parameterized.
Sealed Interface Example
package com.programming.seekho;
public class SealedInterfaceDemo {
public static void main(String[] args) {
Abc abcObj = new Abc();
abcObj.printMessage();
Cde cdeObj = new Cde();
cdeObj.printMessage();
}
}
sealed interface Hello permits Hai, Bye, Abc, Cde{
public void printMessage();
}
non-sealed interface Hai extends Hello{
public void printMessage();
}
non-sealed interface Bye extends Hello{
public void printNumber();
}
non-sealed class Abc implements Hello{
@Override
public void printMessage() {
System.out.println("Hi, I'm in Abc class");
}
}
final class Cde implements Hello{
@Override
public void printMessage() {
System.out.println("Hi, I'm in Cde class");
}
}
Some important notes about sealed class and sealed interface
- If super class is sealed then it must have sub class.
- If super class is sealed then sub class must be final or non-sealed.
- Super class cannot be non-sealed.
- Non-sealed always used with sub class not with super class.
- If you want to avoid sub class to extend with super class then use permits keyword.
- You can permit more than one sub classes.
- sealed, non-sealed and permits can be only used with class not with class members like variables,methods and blocks.
- Sealed class cannot be final and static.
- We can create the object of sealed and non-sealed class.
- If super interface is sealed then it must have sub interface or sub class.
- If super interface is sealed then sub interface must be non-sealed or implemented sub class can be non-sealed or final.
- If you want to avoid sub class or sub interface to extends or implements super interface then permits keyword can be used.
- Sealed interface can permit more than one interfaces and sub classes.
Real-Time Example
In the below example, I have taken a payment system scenario, We have create an interface says ‘PaymentSystem’. I want to make payment with Credit Card and UPI so we have also declared sub classes called ‘PaymentWithUPI’, ‘PaymentWithAmazonPay’, ‘PaymentWithCreditCard’, and ‘PaymentWithPhonePe’.
PaymentSystem interface permits to make payment with credit card and UPI. UPI allows only two types. One is phonepe and another one is amazon pay. You can better understand with below example.
package com.programming.seekho;
public sealed interface PaymentSystem permits PaymentWithCreditCard, PaymentWithUPI{
public void makePayment();
}
package com.programming.seekho;
public sealed class PaymentWithUPI implements PaymentSystem permits PaymentWithAmazonPay, PaymentWithPhonePe{
@Override
public void makePayment() {
PaymentWithAmazonPay amazonPay = new PaymentWithAmazonPay();
amazonPay.makePayment();
PaymentWithPhonePe phonePe = new PaymentWithPhonePe();
phonePe.makePayment();
}
}
package com.programming.seekho;
public non-sealed class PaymentWithAmazonPay extends PaymentWithUPI{
@Override
public void makePayment() {
System.out.println("Payment with AmazonPay is done !!!");
}
}
package com.programming.seekho;
public non-sealed class PaymentWithCreditCard implements PaymentSystem{
@Override
public void makePayment() {
System.out.println("Payment with Credit Card is done !!!");
}
}
package com.programming.seekho;
public non-sealed class PaymentWithPhonePe extends PaymentWithUPI{
public void makePayment() {
System.out.println("Payment with Phone Pe is done !!!");
}
}
Output
Payment with Credit Card is done !!!
Payment with AmazonPay is done !!!
Payment with Phone Pe is done !!!
Conclusion
In this article we have seen about java new feature sealed class and interface. New terms like sealed, non-sealed and permits are introduced now. Also we have seen how to declare sealed class, how it works. I hope this article helps you lot, if you have any concern, please comment in the comment section. I will resolve that.
Thanks!
1 thought on “What is a sealed class in Java?”