DEV Community

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

Posted on

3

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.

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more