Java Sealed

In JDK 17 brought us an implementation of sealed interfaces and classes JEP-409, allowing to restrict which other interface or class is allowed to extend/implement them.

Some imaginary scenario for this feature can be in business domain modeling, allowing to define strict relations betweed objects, like allowing only specific subset of implementors for interface or specific classes to extend base abstract class representing some business domain element.

Sealed Interface

In order to define a sealed interface the only thing required is adding sealed to it’s declaration, then specify the list of classes/interfaces allowed to implement/extend it.

public sealed interface Flyable permits Duck, Owl, Airplane, Boom {
  String fly();
}

At the same time interface implementors can looks as usual.

Record implementiong a sealed interface:

public record Duck(String name) implements Flyable {

  @Override
  public String fly() {
    return String.format("Flying duck %s", name);
  }

}

Note

In case of record our Duch is implicitely final, disallowing anything else to extend it.

Abstract class implementing a sealed interface:

public sealed abstract class Airplane implements Flyable permits GlobeMaster, Hercules {
  protected String id;

  protected Airplane(final String id) {
    this.id = id;
  }

  abstract int getWeight();
}

Note

In case of class or abstract class, those must be one of: sealed, final or non-sealed.

Another interface extending sealed one:

public non-sealed interface Boom extends Flyable {
  void foo();
}

Note

Interface must be one of: non-sealed, sealed.

Sealed Class

Same thing with classes, othe only thing needed is to declate it to be sealed and a list of classes allowed to extend it.

public abstract sealed class Airplane implements Flyable permits GlobeMaster, Hercules {
  protected String id;

  protected Airplane(final String id) {
    this.id = id;
  }

  abstract int getWeight();
}

Note

As was mentiond previously class or abstract class must be one of: final, sealed, non-sealed.

Conclusion

Sealing is a powerful tool giving control over relations. Before this feature, there was no way to restrict inheritance of interface or class, the only thing that was available was final which completely disallowed inheritance without any way to allow it for subset and disallow for others. Nice addition to java developer tool belt.