Posts

Showing posts from March, 2023

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 ...