Creating Sealed Interfaces
A sealed interface limits which classes or interfaces can implement it. Instead of allowing any class to implement an interface, a sealed interface specifies exactly which implementations are permitted.
Sealed interfaces help you create a well-defined set of implementations. This can make your code easier to understand and maintain.
Declaring a Sealed Interface
Use the sealed keyword before the interface keyword. Then use the permits clause to list the classes or interfaces that are allowed to implement it.
In this example, only Circle and Rectangle are allowed to implement the Shape interface.
Implementing a Sealed Interface
A class that implements a sealed interface must declare one of three modifiers:
finalsealednon-sealed
If the class should not have subclasses, use final.
Likewise, Rectangle can also be declared as final.
Allowing More Implementations
A permitted class or interface can also be declared as non-sealed. This removes the restriction for its subclasses.
Other classes can now extend Polygon.
Although Triangle does not directly implement Shape, it is still a Shape because it extends Polygon.
Extending the Restrictions
A permitted class can also be declared as sealed to continue restricting inheritance.
Only Triangle and Pentagon can extend Polygon.
Why Use Sealed Interfaces?
Sealed interfaces are useful when you know all of the valid implementations ahead of time.
For example, a drawing application may support only circles and rectangles. By sealing the Shape interface, you prevent other classes from implementing it unexpectedly.
Sealed interfaces can also help the compiler analyze your code because the complete set of implementations is known.
Sealed vs. Regular Interfaces
A regular interface can be implemented by any class.
A sealed interface limits which classes can implement it.
Use a regular interface when you want other developers to create their own implementations.
Use a sealed interface when you want to control the set of implementations.