sealed
classes were introduced in Java 17. This feature is very useful if there is a need to define a strict hierarchy and restrict
the possibility of extending classes. In order to mention all the allowed subclasses, there is a keyword permits
, which should be
followed by subclasses' names.
This notation is quite useful if subclasses of a given sealed
class can be found in different files, packages, or even modules. In
case when all subclasses are declared in the same file there is no need to mention the explicitly and permits
part of a declaration can
be omitted.
This rule reports an issue if all subclasses of a sealed
class are declared in the same file as their superclass.
Noncompliant code example
sealed class A permits B, C, D, E {} // Noncompliant
final class B extends A {}
final class C extends A {}
final class D extends A {}
final class E extends A {}
Compliant solution
sealed class A {} // Compliant
final class B extends A {}
final class C extends A {}
final class D extends A {}
final class E extends A {}