Latest Java release 15 offers new functionality - sealed
modifier. I went through the JEP and it says:
Sealed classes and interfaces restrict which other classes or interfaces may extend or implement them.
Goals:
- Allow the author of a class or interface to control which code is responsible for implementing it.
- Provide a more declarative way than access modifiers to restrict the use of a superclass.
- Support future directions in pattern matching by underpinning the exhaustive analysis of patterns.
First and second are pretty straightforward, but the third one could hardly be followed. Could somebody explain, please, how sealed
will help with pattern matching
?
Making a class sealed
means that the compiler knows the complete list of implementation classes at compile time. Therefore, it can confirm that (for example) every possible match has been handled.
Consider it similar to checked exceptions: At compile time, the compiler ensures that every checked exception that could be thrown is handled somehow (either by catching or by a throws
clause), so it's guaranteed that the flow control will be formally consistent.