javainterfacesealed-classjava-15java-sealed-type

What is the point of a “sealed interface” in Java?


Sealed classes and sealed interfaces were a preview feature in Java 15, with a second preview in Java 16, and now proposed delivery in Java 17.

They have provided classic examples like Shape -> Circle, Rectangle, etc.

I understand sealed classes: the switch statement example provided makes sense to me. But, sealed interfaces are a mystery to me. Any class implementing an interface is forced to provide definitions for them. Interfaces don't compromise the integrity of the implementation because the interface is stateless on its own. Doesn't matter whether I wanted to limit implementation to a few selected classes.

Could you tell me the proper use case of sealed interfaces in Java 15+?


Solution

  • Although interfaces have no state themselves, they have access to state, eg via getters, and may have code that does something with that state via default methods.

    Therefore the reasoning supporting sealed for classes may also be applied to interfaces.