Categories
Java

Sealed classes in Java

An advanced and less well-known feature in the Java is the use of “sealed classes.” This feature was introduced in Java 14 and allows you to indicate that a class can only be subclassed by a specific set of classes or interfaces.

A sealed class is defined by using the sealed keyword, followed by the class definition and the permits clause, which specifies the set of classes or interfaces that are allowed to subclass the sealed class.

Here’s an example of how to define a sealed class:

public sealed class Shape permits Circle, Square {
    // class definition
}

public final class Circle extends Shape {
    // class definition
}

public final class Square extends Shape {
    // class definition
}

In this example, the Shape class is defined as a sealed class, and it can only be subclassed by the Circle and Square classes. Any attempt to subclass the Shape class with any other class would result in a compile-time error.

This feature can be useful in situations where you want to control the set of classes that can inherit from a certain class, to improve the maintainability and robustness of your code.

It’s worth noting that this feature is relatively new and not widely used yet, and requires understanding of the OOP concepts and proper usage of the sealed classes.

Leave a Reply

Your email address will not be published. Required fields are marked *