How to write a Sealed Class ?
In the last two articles, we discussed the what and why parts - as what's a sealed class and second, why do we even need this concept? Today it's time to see how do we write sealed classes or interfaces.
Just like the way we write abstract classes, or final classes by using specific modifiers, in the same way, Java has given us a modifier named sealed to make a class/interface sealed.
Now coming to the classes which are allowed to extend a sealed class or implement in case of a sealed interface, Java provides us another clause permits
In the below example, Shape class can be extended by only two other classes - Square, Circle
public abstract sealed class Shape permits Square, Circle { ..}
Is it always mandatory to write a permits clause followed by name of the permitted subclasses?
Answer is NO. Then, how would we specify which classes are permitted ?
领英推è
abstract sealed class Root { ...
??final class A extends Root { ... }
??final class B extends Root { ... }
??final class C extends Root { ... }
}?
Worthy to learn here are some constraints which a sealed class mandates its subclasses to follow:
- The sealed class and its permitted subclasses must belong to the same module, and, if declared in an unnamed module, to the same package.
- Every permitted subclass must directly extend the sealed class.
- Every permitted subclass must use a modifier to describe how it propagates the sealing initiated by its superclass:
- It may be declared?final?to prevent further inheritance.
- It may be declared?sealed?to allow its part of the hierarchy to be extended further than envisaged by its sealed superclass, but in a restricted fashion.
- It may be declared?non-sealed?means there is no restriction on subclass. A subclass can be extended further by unknown subclasses.
Exactly one of the modifiers?final,?sealed, and?non-sealed?must be used by each permitted subclass. Ending the article by a code snippet to explain above use cases -
package com.example.geometry;
public abstract sealed class Shape
permits Circle, Rectangle, Square, WeirdShape { ... }
public final class Circle extends Shape { ... }
public sealed class Rectangle extends Shape
permits TransparentRectangle, FilledRectangle { ... }
public final class TransparentRectangle extends Rectangle { ... }
public final class FilledRectangle extends Rectangle { ... }
public non-sealed class WeirdShape extends Shape { ... }
It's not done yet. In next article, we'll learn how to write Sealed Interfaces.
Till then, Happy Learning!