Points to note about Sealed Classes in java

Venu Vudugula
2 min readMay 22, 2023

--

Sealed classes are a feature introduced in Java 15 (as a preview feature) and finalized in Java 17. They provide a way to control which classes can be subclasses or implementers. Sealing a class restricts its subclasses to a specific set of classes, ensuring tighter control over class hierarchies and enhancing code maintainability.

Here’s how sealed classes work:

Declaring a Sealed Class: To declare a sealed class, you use the sealed modifier before the class keyword. For example:

public sealed class Vehicle permits Car, Motorcycle {
// Class body
}

Permitted Subclasses/Implementers: You specify the permitted subclasses or implementers using the permits keyword. In the example above, Car and Motorcycle are permitted subclasses of the Vehicle class.

Defining Subclasses/Implementers: Subclasses or implementers of a sealed class must explicitly declare themselves as such. They use the non-sealed modifier to specify that they are not sealed or use the final modifier to prevent further subclassing.

For example:

public final class Car extends Vehicle {
// Class body
}

public non-sealed class Motorcycle extends Vehicle {
// Class body
}

Extending Sealed Classes: When extending a sealed class, a subclass must be one of the permitted subclasses specified by the sealed class. If a subclass tries to extend the sealed class but is not permitted, a compilation error will occur.

Sealed classes offer benefits such as better control over class hierarchies, improved maintainability, and enhanced compiler warnings. They can be particularly useful in scenarios where you want to provide a limited set of subclasses or implementers for a class, such as in frameworks or libraries.

It’s important to note that sealed classes are not meant to be used in every situation. They should be used judiciously when there is a need for tighter control over class inheritance and to ensure code integrity.

--

--

Venu Vudugula
Venu Vudugula

Written by Venu Vudugula

I'm Venu, a seasoned tech professional with over 9 years of experience in full-stack development, eager to take on exciting challenges 😊.

No responses yet