Sealed Class in Java

 In Java, a sealed class is a new feature introduced in Java 17 to support sealed types. Sealed types are a way to restrict the hierarchy of a class or interface to a limited set of subtypes.

A sealed class is defined using the sealed modifier before the class keyword, and it can only be extended by a limited set of classes or interfaces that are explicitly listed in the class definition. For example:

mohit
public sealed class Shape permits Circle, Rectangle, Triangle { // class definition }

In the above example, Shape is a sealed class that is only permitted to be extended by Circle, Rectangle, and Triangle classes. Any other attempts to extend the Shape class will result in a compile-time error.

The purpose of sealed classes is to enhance the expressiveness of type hierarchies in Java and help to improve the reliability and security of programs. It allows you to provide more information about the structure of your code, making it easier for other developers to understand and maintain your code.

Comments

Popular posts from this blog

Cryptography API

Java Applet Overview

Vector in Java