Applying sealed classes
Sealed classes were introduced in Java 17. What we are going to cover here relates to classes but the same logic applies to interfaces (Chapter 10). With inheritance, you can extend from any class (or interface) using the extends
keyword, unless the class is final
of course.
Note
Interfaces cannot be final
because their whole rationale is to be implemented.
Consider the following scenario: what if you wanted your class to be available for inheritance, but only for certain classes? In other words, you want to scope the subclasses allowed. So far, inheritance, using extends
, enables every class to become a subclass, whereas final
prevents a class from having subclasses.
This is where sealed classes are useful – they enable you to specify what subclasses are allowed. Just to reiterate, this also applies to interfaces, where we can specify what classes are allowed to implement the interface.
Before we look at an example, there are some new...