https://www.youtube.com/watch?v=Xkh5sa3vjTE

In the intro to this talk, Venkat Subramaniam goes over the motivation for introducing the concept of Sealed Classes into the language. Most implementors of libraries may have a specific intent for their library. If a library is extensible, it may unknowingly introduce code that cannot be handled.

Sealed Interfaces

The second part of the talk covered an example and information reprised from another talk, where he explained how a sealed interface work -

A sealed interface allows you to limit how many classes implement the interface

sealed interface TrafficLight {}

final class Redlight implements TrafficLight {}
final class GreenLight implements TrafficLight {}
final class YellowLight implements TrafficLight {}

In the above example -

sealed interface TrafficLight permits RedLight, GreenLight, YellowLight, FlashingLight;

Defining multiple final classes in a single file can get unwieldy. Therefore it is possible to specify the names of the classes that are permitted, as shown in the above example - using the permits keyword.

Compiler Errors

The compiler will protect the developer from

sealed interface TrafficLight{}
sealed interface TrafficLight{}

class Redlight implements TrafficLight {}
sealed class YellowLight implements TrafficLight {}

Benefits of Sealed Classes