Sealed classes and interfaces
A final
class cannot be extended, while a non-public class or interface has limited access. Yet, there are times when a class or interface needs to be accessible from anywhere but be extendable only by a certain class or interface, or, in the case of an interface, be implemented only by certain classes. That was the motivation for sealed
classes and interfaces being added to the SDK in Java 17.
The difference between a sealed
class or interface and a final
one is that a sealed
class or interface always has a permits
keyword, followed by the list of the existing direct subtypes that are allowed to extend the sealed
class or interface, or, in the case of the interface, implement it. Please note the word existing. The subtypes listed after the permits
keyword must exist at compilation time in the same module as the sealed class or in the same package if in the default (unnamed) module.
A subtype of a sealed
class must be marked either sealed
, final
...