0

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?

jaco0646
  • 15,303
  • 7
  • 59
  • 83
Serhii Povísenko
  • 3,352
  • 1
  • 30
  • 48
  • So I'm guessing you don't understand what "by underpinning the exhaustive analysis of patterns." means? – Sweeper Jun 18 '20 at 01:49
  • 1
    Did you read the example in the "Description" section? There is one example about pattern matching that explains this pretty well. – Sweeper Jun 18 '20 at 01:52

1 Answers1

1

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.

chrylis -cautiouslyoptimistic-
  • 75,269
  • 21
  • 115
  • 152