The optional permits clause in a normal class declaration specifies all the classes intended as direct subclasses of the class being declared (§8.1.1.2).
ClassPermits:
permits TypeName {, TypeName}
It is a compile-time error if a class declaration has a permits clause but no sealed modifier.
Every TypeName must name an accessible class (§6.6), or a compile-time error occurs.
It is a compile-time error if the same class is specified more than once in a permits clause. This is true even if the class is named in different ways.
The canonical name of a class does not need to be used in a permits clause, but a permits clause can only specify a class once. For example, the following program fails to compile:
package p;
sealed class A permits B, C, p.B {} // error
non-sealed class B extends A {}
non-sealed class C extends A {}
If a sealed class C is associated with a named module (§7.3), then every class specified in the permits clause of C's declaration must be associated with the same module as C, or a compile-time error occurs.
If a sealed class C is associated with an unnamed module (§7.7.5), then every class specified in the permits clause of C's declaration must belong to the same package as C, or a compile-time error occurs.
A sealed class and its direct subclasses need to refer to each other in a circular fashion, in permits and extends clauses, respectively. Therefore, in a modular codebase, they must be co-located in the same module, as classes in different modules cannot refer to each other in a circular fashion. Co-location is desirable in any case because a sealed class hierarchy should always be declared within a single maintenance domain, where the same developer or group of developers is responsible for maintaining the hierarchy. A named module typically represents a maintenance domain in a modular codebase.
If the declaration of a sealed class C has a permits clause, then the permitted direct subclasses of C are the classes specified by the permits clause.
Every permitted direct subclass specified by the permits clause must be a direct subclass of C (§8.1.4), or a compile-time error occurs.
If the declaration of a sealed class C lacks a permits clause, then the permitted direct subclasses of C are as follows:
-
If C is not an enum class, then its permitted direct subclasses are those classes declared in the same compilation unit as C (§7.3) which have a canonical name (§6.7) and whose direct superclass is C.
That is, the permitted direct subclasses are inferred as the classes in the same compilation unit that specify C as their direct superclass. The requirement for a canonical name means that no local classes or anonymous classes will be considered.
It is a compile-time error if the declaration of a
sealedclass C lacks apermitsclause and C has no permitted direct subclasses. -
If C is an enum class, then its permitted direct subclasses, if any, are specified in §8.9.