DEV Community

Cover image for What are sealed classes in Java ?
Rakesh KR
Rakesh KR

Posted on

What are sealed classes in Java ?

Sealed classes are a new feature in Java 17 that allows you to restrict which classes can inherit from a specific class. This can be useful for preventing unintended inheritance and creating more flexible and reusable code.

A sealed class is defined using the sealed modifier, followed by the permits keyword and a list of allowed subclasses. For example, the following code defines a sealed class called Shape and allows only Circle and Rectangle to inherit from it:

sealed class Shape permits Circle, Rectangle {}
Enter fullscreen mode Exit fullscreen mode

To use a sealed class, you simply define your subclasses as usual and extend the sealed class. For example:

public final class Circle extends Shape {
    // class implementation goes here
}

public final class Rectangle extends Shape {
    // class implementation goes here
}
Enter fullscreen mode Exit fullscreen mode

Any class that tries to inherit from Shape but is not listed in the permits clause will not be allowed, and the code will not compile. This can help prevent unintended inheritance and make your code more robust and maintainable.

Top comments (0)