On page 373, the following infobox is printed:
Real World Scenario "Why Have Sealed Classes?"
In Chapter 3, “Making Decisions,” you learned about switch expressions and pattern
matching. Imagine if we could treat a sealed class like an enum in a switch expression by
applying pattern matching. Given a sealed class Fish with two direct subclasses, it might
look something like this:
If Fish wasn’t sealed, the switch expression would require a default branch, or the
code would not compile. Since it’s sealed, the compiler knows all the options! The good
news is that this feature is on the way, but the bad news is that it’s still in Preview in Java 17 and not officially released. We just wanted to give you an idea of where some of these new features were heading.
When enabling the preview feature and running a similar code example, the compiler returned this:
error: the switch expression does not cover all possible input values
The switch expression would only compile if a case for the Fish class itself was added after the other two case statements. The method with the switch expression is just a code example to illustrate a point, that gets obvious anyway. But maybe it should be changed anyway so that the example is correct.
The Fish case would have to come after the other two cases, otherwise the compiler reports:
error: this case label is dominated by a preceding case label
Another solution for the last problem would be to make the Fish class abstract.