Sealed Classes/Interfaces in Java

Sealed is a new keyword that you can use in the latest java versions. It is an addition to Java’s object-oriented structure. It can be used in both classes and interfaces. We use sealed to prevent unauthorized implementations.

Whenever an interface or a class is marked with sealed, can only be accessed by permitted classes or interfaces.

Three different keyword are available:

  1. sealed: Only permitted classses can implement.
  2. non-sealed: Every class can implement.
  3. permits: Used for specifying permitted classes. If you permit a class(or an interface) the permitted class must implement it.

Let’s define Language interface:

Let’s create some implementations

If we mark Language as sealed, we will get errors in English, Turkish and French classes. Because implementers must be final, sealed, or non-sealed

In this sturcutre:
1. English can be extended without any limitation.
2. Turkish is a final class. There is no way to extend it.
3. French can only be extended by AdvancedFrench.

If you mark a class or an interface with sealed, you must have at least one subclass of it. This is why I added Advanced French.

You can add any permitted implementations after the Permits keyword.

With the code above, you can no longer extend or implement the Lanugage interface except English, Turkish, French classes(or interfaces).

If you permit a class(or an interface) the permitted class must implement it. Because of that below code fails. Turkish class must implement Lanuage.

The implementation must be direct. You can’t permit a class’s child. The below code will fail. AdvancedFrench must dirrectly implement Language interface.

You can use interfaces in the permits section.

You can use records in the permits section. Records are final, so you don’t have to add anything else.

Referances:

https://docs.oracle.com/en/java/javase/17/language/sealed-classes-and-interfaces.html

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store