What are sealed classes and interfaces
sealed modifier gives you greater control over inheritance within Java. By predefining which classes are
allowed to extend or implements a sealed class or interface.
When to use sealed
In previous versions of Java, we only had access-modifiers to restrict inheritance, now we can use
sealed to decide what code is allowed to
implement it. Because sometimes, you want to reuse code only between certain classes.
Creating sealed classes
Java 17 also introduces other modifiers to help you write sealed classes:
permit are all you need to create a sealed class. The permit must be at the end, so after the class name
and any implements or extends.
The sub-classes of a sealed class must be
non-sealed allows the class or interface to be extended or implemented by any other code. Because sometimes, you want
specific extension points that others can use.
Parrot can now extend it without being sealed, non-sealed, or final.
Also, interfaces can be sealed. The
permits now give you control over what code can implement or extend it. It works
the same as with a class. Interfaces can also be sealed or non-sealed. You cannot use final because then no class could
implement the interface.
Because records are implicitly final, they are a little more concise.
Patten matching with Switch
The compiler knows all the possible subclasses of a sealed class. This allows you to create a
switch without a default
case. Because it knows that we covered all the possible subclasses, if the Animal class was not abstract or a subclass
was non-sealed, the Switch would need a default case.
Sealed classes that have no non-sealed subclasses also have a security benefit because they have restricted extensibility.
For example, the method
openSafe(SafeLock lock, String key) accepts a subclass of
SafeLock, but a malicious person could
EvilLock and send the keys somewhere else. A Sealed interface that only permits
GoodLock to implement the
interface can prevent the
EvilLock from being created. Thus preventing malicious people from harming.
Sealed classes are a creat new way to restrict inheritance and give the authors more control over their code. The examples covered creating sealed classes, interfaces, records, and how to extend or implement them. We also covered the security benefit they add to a codebase.