Sealed Classes and Interfaces in Java

Sealed Classes & Interfaces

 Sealed classes and interfaces restrict which other classes or interfaces may extend or implement them.


Purpose Of Creating Sealed Classes or Interfaces:- 

As We know purposes of inheritance is code reuse: When you want to create a new class and there is an existing class that have some of the code that you want to reuse then you can derive your new class from the existing class. In doing this, you can reuse the fields and methods of the existing class. 
In the above scenario, any new class(Child class) can extends Existing Class(Parent class) and can use its fields and methods. 

If we want to restrict any Class or Interface in such a way that only some permitted classes and interfaces can use their fields and methods, To achieve this Concept of Sealed Classes and Interfaces came in Java 17.

How to Achieve Sealed Classes and Interfaces:-

To seal a class, add the sealed modifier to its declaration. Then, after any extends and  implements clauses, add the permits clause. This clause specifies the classes that may extend the sealed class.

For Example:-

public sealed class Accounts permits SavingAccount, CurrentAccount{

public final class SavingAccount extends Accounts{

}

public non-sealed class CurrentAccount extends Accounts{

}

Note:- Permitted class must be declare with anyone of these modifier like final, non-sealed,sealed.  


Comments

Popular posts from this blog

Introduction of RabbitMQ

RabbitMQ Installation on Windows