Sealed Classes and Interfaces in Java

What is a Sealed Class in Java?

When we have a public interface or a public class, other classes have no restrictions to implement/extend it.

Since Java 15, we have Sealed classes and interfaces that allow us to restrict which other classes or interfaces may extend or implement them.

With Sealed classes, we got two new keywords:

  • sealed – declaring the Sealed class
  • permits – specifying what classes can extend the Sealed class

Syntax

public sealed class Vehicle permits Car, Truck, Bus {}
  • Classes that extend a Sealed class must be declared sealednon-sealed, or final.
  • Class declared as final can not be extended.
  • A sealed class can only be extended by its permitted subclasses.
  • All subclasses can extend a non-sealed class.

Declaring the subclasses:

final class Bus extends Vehicle {
}

non-sealed class Truck extends Account {
}

sealed class Car permits BlueCar, RedCar{
}

Examples

Let’s create one abstract sealed class User:

public abstract sealed class User permits PremiumUser, AdvancedUser {
  public abstract String getUserData();
}

This class permits only PremiumUser and AdvancedUser classes to extend it.

Let’s implement these two classes:

non-sealed class PremiumUser extends User {
  
  @Override
  public String getUserData() {
    return "Premium user data ...";
  }
}

final class AdvancedUser extends User {
  @Override
  public String getUserData() {
    return "Advanced user data ...";
  }
}
  • We have created a non-sealed class PremiumUser that can be extended by other classes in the same package with no restrictions there.
  • We also created the class AdvancedUser and we made it final because we don’t want any other class to extend it.
  • There are no issues with compiling this code because both classes can extend the sealed class User.

Now let’s try to extend class User with a new class with the name RegularUser:

non-sealed abstract class RegularUser extends User {
}


Here, we got a compilation error with the message: RegularUser is not allowed in the sealed hierarchy.

In case we didn’t declare one of the permitted classes with sealed, non-sealed, or final modifiers, we would get the following compiler error: sealed, non-sealed or final modifiers expected.

What is a Sealed Interface in Java?

There are no differences between declaring a sealed class and a sealed interface.

We will add the sealed modifier to its declaration if we want to seal an interface and use the permits keyword to specify which classes can implement it.

Sealed interface

sealed interface Interface1 permits Class1, Class2 {
}

Classes that are permitted to implement the Interface1 interface must be declared with sealed, non-sealed, or final modifiers.

That’s it!

Leave a Reply

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