Sealed Classes in Java

What are sealed classes?

Sealed classes is a new feature introduced in Java 15, that enables us to define a closed inheritance hierarchy. Sealing allows classes and interfaces to restrict which other classes or interfaces may extend or implement them.

How do we define a sealed class?

We can use the sealed modifier to define a sealed class. A sealed class can specify a list of it’s permitted subclasses using the permits clause. Only the classes that appear in this list are allowed to extend the sealed class.

public sealed class WaterFlower permits Lily {}

How are the permitted subclasses defined for a sealed class?

The permits clause is used to list the permitted subclasses of a sealed class.

public sealed class WaterFlower permits Lotus, Lily, Hyacinth {}

In the above code the sealed class WaterFlower permits three subclasses – Louts, Lily and Hyacinth.

Which modifiers are to be given for the permitted subclasses?

The permitted subclasses should have one of the following modifiers

  • final: – if the final modifier is given, this class cannot be extended further
  • Sealed – if sealed modifier is given, this class can only be extended by its permitted subclasses
  • Non-sealed – if non-sealed modifier is given, this class can be extended by unknown subclasses

In the above example, the permitted subclasses may be defined as below.

non-sealed class Lily extends WaterFlower{}  

sealed class Lotus extends WaterFlower{} 

final class Hyacinth extends WaterFlower{} 

Is it possible to omit the permits clause?

The permits clause can be omitted if the permitted subclasses are in the same file as the sealed class. 


Learn more about Sealed Classes here.

Leave a Reply

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