Let’s continue with our lessons during this corona lockdown. In the last three posts we discussed textblocks, instanceof and record types in Java 13 and 14.
In this post, let’s talk about a proposed feature, sealed interfaces
In languages like C#, sealed types are equivalent to final classes in Java. The problem with final classes in Java is no other class present in any other library can extend it. It’s tightly packed.
Now, Java is about to introduce a new sealed keyword, for creating sealed interfaces. We can create sealed interfaces and specify the types that can implement the interfaces. So sealed interfaces unlike final types, specify restricted implementations.
sealed interface Animal permits Dog, Cat {} class Dog implements Animal {} class Cat implements Animal {} class Ant implement Animal {} //ERROR
In the code above, Animal is a sealed interface and only Dog and Cat classes can implement it. Ant will not be allowed to implement. So naturally even an anonymous/lambda implementation of Animal is also not possible.
Therefore the compiler as well as the JVM enforce the implementation of sealed types.