SealedShouldHavePermitsList

Since Checkstyle 10.18.0

Description

Checks that sealed classes and interfaces have a permits list.

Rationale: When a permits clause is omitted from a sealed class, any class within the same compilation unit can extend it. This differs from other sealed classes where permitted subclasses are explicitly declared, making them readily visible to the reader. Without a permits clause, identifying potential subclasses requires searching the entire compilation unit, which can be challenging, especially in large files with complex class hierarchies.

See the Java Language Specification for more information about sealed classes.

Examples

To configure the check:

<module name="Checker">
  <module name="TreeWalker">
    <module name="SealedShouldHavePermitsList"/>
  </module>
</module>
        

Example:

public class Example1 {

  // imagine hundreds of lines of code...

  sealed class A {} // violation
  final class B extends A {}
  final class C extends A {}
  final class D { } // this can extend A, so as any other class in the same file
}

// all subclasses are declared at the enclosing class level, for easy reading
class CorrectedExample1 {
  sealed class A permits B, C {} // ok, explicitly declared permitted subclasses
  final class B extends A {}
  final class C extends A {}
  final class D { } // this can not extend A
}
        

Example of Usage

Violation Messages

All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.

Package

com.puppycrawl.tools.checkstyle.checks.design

Parent Module

TreeWalker