JEP 360:密封类(预览)

官方原文(英文)地址: https://openjdk.java.net/jeps/360
个人原创翻译,转载请注明出处。

Summary

Enhance the Java programming language with sealed classes and interfaces. Sealed classes and interfaces restrict which other classes or interfaces may extend or implement them.

摘要

使用密封类和接口增强Java编程语言。密封类和接口可以限制哪些其他类或接口可以扩展或实现它们。

Goals

  • Allow the author of a class or interface to control which code is responsible for implementing it.
  • Provide a more declarative way than access modifiers to restrict the use of a superclass.
  • Support future directions in pattern matching by underpinning the exhaustive analysis of patterns.

目标

  • 允许类或接口的作者可以控制哪些代码有责任实现它。
  • 提供比访问修饰符更具声明性的方式来限制父类的使用。
  • 通过对模式进行详尽的分析来支持模式匹配的未来方向。

Non-Goals

  • It is not a goal to provide new forms of access control such as "friends".
  • It is not a goal to change final in any way.

非目标

  • 提供诸如“friends”等新形式的访问控制不是目标。
  • 以任何方式改变final不是目标。

Motivation

In Java, a class hierarchy enables the reuse of code via inheritance: The methods of a superclass can be inherited (and thus reused) by many subclasses. However, the purpose of a class hierarchy is not always to reuse code. Sometimes, its purpose is to model the various possibilities that exist in a domain, such as the kinds of shapes supported by a graphics library or the kinds of loans supported by a financial application. When the class hierarchy is used in this way, restricting the set of subclasses can streamline the modeling.

动机

在Java中,类层次结构可以通过继承来实现代码的复用:父类的方法可以被许多子类继承(并因此被复用)。但是,类层次结构的目的并不总是复用代码。有时,其目的是对域中存在的各种可能性进行建模,例如图形库支持的形状类型或金融应用程序支持的贷款类型。当以这种方式使用类层次结构时,限制子类集可以简化建模。

For example, in a graphics library, the author of a class Shape may intend that only particular classes can extend Shape, since much of the library's work involves handling each kind of shape in the appropriate way. The author is interested in the clarity of code that handles known subclasses of Shape, and not interested in writing code to defend against unknown subclasses of Shape. Allowing arbitrary classes to extend Shape, and thus inherit its code for reuse, is not a goal in this case. Unfortunately, Java assumes that code reuse is always a goal: If Shape can be extended at all, then it can be extended by any number of classes. It would be helpful to relax this assumption so that an author can declare a class hierarchy that is not open for extension by arbitrary classes. Code reuse would still be possible within such a closed class hierarchy, but not beyond.

例如,在图形库中,Shape类的作者可能希望只有特定的类可以继承Shape,因为该库的大部分工作都涉及以适当的方式处理每种形状。作者感兴趣的是处理Shape已知子类的代码的清晰度,而不是编写代码来防御未知Shape子类。允许任意类继承Shape,从而继承其代码以供重用,在这种情况下不是目标。不幸的是,Java假定代码重用始终是一个目标:如果Shape可以扩展,那么它可以由任意数量的类继承。放宽这个假设是有帮助的,这样作者就可以声明一个类层次结构,它不能被任意类扩展。在这样一个封闭的类层次结构中,代码重用仍然是可能的,但不能超越一切。

Java developers are familiar with the idea of restricting the set of subclasses because it often crops up in API design. The language provides limited tools in this area: either make a class final, so it has zero subclasses, or make a class or its constructor package-private, so it can only have subclasses in the same package. An example of a package-private superclass appears in the JDK:

Java开发者很熟悉限制子类范围的想法,因为它经常出现在API设计中。该语言在这方面提供了有限的工具:要么将类设为final,使其具有零个子类,要么将类或其构造器设为包级私有,因此它只能在同一个包中包含子类。包级私有超类的示例出现在JDK中

package java.lang;

abstract class AbstractStringBuilder {...}
public final class StringBuffer  extends AbstractStringBuilder {...}
public final class StringBuilder extends AbstractStringBuilder {...}
package java.lang;

abstract class AbstractStringBuilder {...}
public final class StringBuffer  extends AbstractStringBuilder {...}
public final class StringBuilder extends AbstractStringBuilder {...}

The package-private approach is useful when the goal is code reuse, such as the subclasses of AbstractStringBuilder sharing its code for append. However, the approach is useless when the goal is modeling alternatives, since user code cannot access the key abstraction -- the superclass -- in order to switch over it. It is not possible to allow users to access the superclass without also allowing them to extend it. (Even within a graphics library that declares Shape and its subclasses, it would be unfortunate if only one package could access Shape.)

当目标是代码重用时,包级私有方法很有用,例如AbstractStringBuilder的子类共享它的append代码。然而,当目标是对备选进行建模时,包级私有的处理就没用了,因为用户代码无法访问关键抽象——父类——以便对其进行switch处理。不可能在允许用户访问父类时,又不让他们继承它。(即使在声明Shape及其子类的图形库中,只有一个包可以访问Shape也是不幸的。)

In summary, it should be possible for a superclass to be widely accessible (since it represents an important abstraction for users) but not widely extensible (since its subclasses should be restricted to those known to the author). Such a superclass should be able to express that it is co-developed with a given set of subclasses, both to document intent for the reader and to allow enforcement by the Java compiler. At the same time, the superclass should not unduly constrain its subclasses by, e.g., forcing them to be final or preventing them from defining their own state.

总之,父类应该可以被广泛访问(因为它代表用户的重要抽象)但不能广泛扩展(因为它的子类应该仅限于作者已知的那些)。这样的父类应该能够表示它是与一组给定的子类共同开发的,既可以记录读者的意图,又可以让Java编译器强制执行。同时,父类不应过度限制其子类,例如强制它们为final或阻止它们定义自己的状态。

Description

A sealed class or interface can be extended or implemented only by those classes and interfaces permitted to do so.

描述

密封类或接口只能由允许的类和接口进行继承或实现。

A class is sealed by applying the sealed modifier to its declaration. Then, after any extends and implements clauses, the permits clause specifies the classes that are permitted to extend the sealed class. For example, the following declaration of Shape specifies three permitted subclasses:

一个类通过对它的声明应用sealed修饰符来密封。然后,在任何extendsimplements子句之后,用permit子句指定允许扩展密封类的类。例如,以下Shape声明指定了三个允许的子类:

package com.example.geometry;

public abstract sealed class Shape
permits Circle, Rectangle, Square {...}
package com.example.geometry;

public abstract sealed class Shape
permits Circle, Rectangle, Square {...}

The classes specified by permits must be located near the superclass: either in the same module (if the superclass is in a named module) or in the same package (if the superclass is in the unnamed module). For example, in the following declaration of Shape, its permitted subclasses are all located in different packages of the same named module:

permit指定的类必须位于父类附近:在同一个模块中(如果父类在已命名的模块中),或在同一个包中(如果父类在未命名的模块中)。例如,在下面的Shape声明中,其允许的子类都位于同名模块的不同包中:

package com.example.geometry;

public abstract sealed class Shape 
permits com.example.polar.Circle,
        com.example.quad.Rectangle,
        com.example.quad.simple.Square {...}
package com.example.geometry;

public abstract sealed class Shape 
permits com.example.polar.Circle,
        com.example.quad.Rectangle,
        com.example.quad.simple.Square {...}

When the permitted subclasses are small in size and number, it may be convenient to declare them in the same source file as the sealed class. When they are declared in this way, the sealed class may omit the permits clause, and the Java compiler will infer the permitted subclasses from the declarations in the source file (which may be auxiliary or nested classes). For example, if the following code is found in Shape.java, then the sealed class Shape is inferred to have three permitted subclasses:

当允许的子类的大小和数量都较小时,将它们声明在与密封类相同的源文件中可能会很方便。当它们以这种方式声明时,密封类可能会省略permit子句,Java编译器将从源文件中的声明(可能是辅助类或嵌套类)推断出允许的子类。例如,如果在Shape.java中找到以下代码,则推断密封类Shape具有三个允许的子类:

package com.example.geometry;

abstract sealed class Shape {...}
... class Circle    extends Shape {...}
... class Rectangle extends Shape {...}
... class Square    extends Shape {...}
package com.example.geometry;

abstract sealed class Shape {...}
... class Circle    extends Shape {...}
... class Rectangle extends Shape {...}
... class Square    extends Shape {...}

The purpose of sealing a class is to let client code reason clearly and conclusively about all permitted subclasses. The traditional way to reason about subclasses is with an if-else chain of instanceof tests, but analyzing such chains is difficult for the compiler, so it cannot determine that the tests cover all permitted subclasses. For example, the following method would cause a compile-time error because the compiler does not share the developer's conviction that every subclass of Shape is tested and leads to a return statement:

密封一个类的目的是让客户端代码对所有允许的子类进行清晰和结论性的推断。推断子类的传统方法是使用instanceof测试的if-else链,但是编译器很难分析这样的链,因此无法确定测试是否涵盖所有允许的子类。例如,以下方法会导致编译期错误,因为编译器并不认同开发者的信念,即Shape的每个子类都经过测试并导致返回语句:

int getCenter(Shape shape) {
    if (shape instanceof Circle) {
        return ... ((Circle)shape).center() ...
    } else if (shape instanceof Rectangle) {
        return ... ((Rectangle)shape).length() ...
    } else if (shape instanceof Square) {
        return ... ((Square)shape).side() ...
    }
}
int getCenter(Shape shape) {
    if (shape instanceof Circle) {
        return ... ((Circle)shape).center() ...
    } else if (shape instanceof Rectangle) {
        return ... ((Rectangle)shape).length() ...
    } else if (shape instanceof Square) {
        return ... ((Square)shape).side() ...
    }
}

Appending a catch-all else clause would be contrary to the developer's conviction that the tests are already exhaustive. In addition, the compiler has no ability to save the developer if their conviction turns out to be wrong. Suppose the code above is accidentally edited to omit, say, the instanceof Rectangle test; no compile-time error will occur. (The omission might be easy to spot with three permitted subclasses, but not with 10 or 20. Even with just three, the code is frustrating to write and tedious to read.)

附加一个捕获所有的else子句将违背开发者的初衷,即测试已经详尽无遗。此外,如果他们的初衷被证明是错误的,编译器也没有能力拯救开发者。假设上面的代码被意外编辑忽略了,比如说,instanceof Rectangle测试;不会发生编译时错误。(使用三个允许的子类可能很容易发现遗漏,但10或20个则不然。即使只有三个,代码编写起来也令人沮丧,阅读起来也很乏味。)

The ability to reason clearly and conclusively about permitted subclasses will be realized in a future release that supports pattern matching. Instead of inspecting an instance of a sealed class with if-else, client code will be able to switch over the instance using type test patterns (JEP 375). This allows the compiler to check that the patterns are exhaustive. For example, given the following code, the compiler will infer that every permitted subclass of Shape is covered, so no default clause (or other total pattern) is needed; moreover, the compiler will give an error if any of the three cases are missing:

将在支持模式匹配的未来版本中实现对允许的子类进行清晰和结论性推理的能力。客户端代码将能够使用类型测试模式JEP 375)切换实例,而不是使用if-else检查密封类的实例。 这允许编译器检查模式是否详尽。例如,给定以下代码,编译器将推断Shape的每个允许的子类都被覆盖,因此不需要default子句(或其他总模式);此外,如果缺少以下三种情况中的任何一种,编译器都会报错:

int getCenter(Shape shape) {
    return switch (shape) {
        case Circle c    -> ... c.center() ...
        case Rectangle r -> ... r.length() ...
        case Square s    -> ... s.side() ...
    };
}
int getCenter(Shape shape) {
    return switch (shape) {
        case Circle c    -> ... c.center() ...
        case Rectangle r -> ... r.length() ...
        case Square s    -> ... s.side() ...
    };
}

A sealed class imposes three constraints on its permitted subclasses (the classes specified by its permits clause):

  1. The sealed class and its permitted subclasses must belong to the same module, and, if declared in an unnamed module, the same package.
  2. Every permitted subclass must directly extend the sealed class.
  3. Every permitted subclass must choose a modifier to describe how it continues the sealing initiated by its superclass:
    • A permitted subclass may be declared final to prevent its part of the class hierarchy from being extended further.
    • A permitted subclass 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.
    • A permitted subclass may be declared non-sealed so that its part of the hierarchy reverts to being open for extension by unknown subclasses. (A sealed class cannot prevent its permitted subclasses from doing this.)

密封类对其允许的子类(由其permit子句指定的类)施加三个约束:

  1. 密封类及其允许的子类必须属于同一个模块,并且,如果在未命名的模块中声明,则属于同一个包。
  2. 每个允许的子类必须直接扩展密封类。
  3. 每个允许的子类必须选择一个修饰符来描述它如何延续由其父类发起的密封:
    • 允许的子类可以声明为final,以防止其在类层次结构中的部分被进一步向下继承。
    • 允许的子类可以声明为sealed,以允许其层次结构的一部分比其密封的父类所设想的扩展得更远,但以受限制的方式。
    • 一个允许的子类可以被声明为non-sealed,这样它的层次结构部分就会恢复到对未知子类的扩展开放。(密封类不能阻止其允许的子类这样做。)

As an example of the third constraint, Circle may be final while Rectangle is sealed and Square is non-sealed:

作为第三条约束的例子,Circle可以为final的,Rectanglesealed的,而Squarenon-sealed的:

package com.example.geometry;

public abstract sealed class Shape
    permits Circle, Rectangle, Square {...}

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 Square extends Shape {...}
package com.example.geometry;

public abstract sealed class Shape
    permits Circle, Rectangle, Square {...}

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 Square extends Shape {...}

One and only one of the modifiers final, sealed, and non-sealed must be used by each permitted subclass. It is not possible for a class to be both sealed (implying subclasses) and final (implying no subclasses), or both non-sealed (implying subclasses) and final (implying no subclasses), or both sealed (implying restricted subclasses) and non-sealed (implying unrestricted subclasses).

每个允许的子类必须使用一个且仅一个修饰符finalsealednon-sealed。一个类不可能既是sealed的(暗示有子类)又是final的(暗示没有子类),或者既是non-sealed的(暗示子类)又是final的(暗示没有子类),或者既是sealed的(暗示受限制的子类)又是non-sealed的(暗示不受限制的子类)。

(The final modifier can be considered as a strong form of sealing, where extension/implementation is prohibited completely. That is, final is conceptually equal to sealed + a permits clause which specifies nothing; note that such a permits clause cannot be written in Java.)

final修饰符可以被认为是一种强密封形式,其中完全禁止扩展/实现。也就是说,final在概念上等同于sealed加上一个不指定任何内容的permits子句;注意这样的permits子句不能用Java编写。)

Abstract classes. A class which is sealed or non-sealed may be abstract, and have abstract members. A sealed class may permit subclasses which are abstract (providing they are then sealed or non-sealed, rather than final).

抽象类。sealednon-sealed的类可以是abstract的,并且具有abstract的成员。sealed类可以允许abstract的子类(前提是它们是sealed的或non-sealed的,而不是final的)。

Class accessibility. Because extends and permits clauses make use of class names, a permitted subclass and its sealed superclass must be accessible to each other. However, permitted subclasses need not have the same accessibility as each other, or as the sealed class. In particular, a subclass may be less accessible than the sealed class; this means that, in a future release when pattern matching is supported by switches, some users will not be able to exhaustively switch over the subclasses unless a default clause (or other total pattern) is used. Java compilers will be encouraged to detect when a user's switch is not as exhaustive as the user imagined it would be, and customize the error message to recommend a default clause.

类可访问性。由于extendspermits子句使用类名,因此允许的子类及其密封超类必须可以相互访问。但是,允许的子类彼此之间不需要具有相同的可访问性,也不需要与密封类具有相同的可访问性。特别是,子类可能比密封类更难访问;这意味着,在未来版本中,当switch支持模式匹配时,除非使用default子句(或其他总模式),否则某些用户将无法彻底switch子类。将鼓励Java编译器检测用户的switch何时不像用户想象的那样详尽,并自定义错误消息以推荐default子句。

Sealed interfaces

Similar to the story for classes, an interface is sealed by applying the sealed modifier to the interface. After any extends clause to specify superinterfaces, the implementing classes and subinterfaces are specified with a permits clause. For example:

密封接口

与类的情况类似,通过将sealed修饰符应用于接口来密封接口。在任何用于指定超接口的extends子句之后,使用permit子句指定实现类和子接口。例如:

package com.example.expression;

public sealed interface Expr
    permits ConstantExpr, PlusExpr, TimesExpr, NegExpr {...}

public final class ConstantExpr implements Expr {...}
public final class PlusExpr     implements Expr {...}
public final class TimesExpr    implements Expr {...}
public final class NegExpr      implements Expr {...}
package com.example.expression;

public sealed interface Expr
    permits ConstantExpr, PlusExpr, TimesExpr, NegExpr {...}

public final class ConstantExpr implements Expr {...}
public final class PlusExpr     implements Expr {...}
public final class TimesExpr    implements Expr {...}
public final class NegExpr      implements Expr {...}

Sealed classes and Records

Sealed classes work well with records (JEP 384), another preview feature of Java 15. Records are implicitly final, so a sealed hierarchy with records is slightly more concise than the example above:

密封类与记录

密封类与记录 (JEP 384) 配合得很好,这是Java 15的另一个预览特性。记录是隐式final的,因此带有记录的密封层次结构比上面的示例稍微简洁一些:

package com.example.expression;

public sealed interface Expr
    permits ConstantExpr, PlusExpr, TimesExpr, NegExpr {...}

public record ConstantExpr(int i)       implements Expr {...}
public record PlusExpr(Expr a, Expr b)  implements Expr {...}
public record TimesExpr(Expr a, Expr b) implements Expr {...}
public record NegExpr(Expr e)           implements Expr {...}
package com.example.expression;

public sealed interface Expr
    permits ConstantExpr, PlusExpr, TimesExpr, NegExpr {...}

public record ConstantExpr(int i)       implements Expr {...}
public record PlusExpr(Expr a, Expr b)  implements Expr {...}
public record TimesExpr(Expr a, Expr b) implements Expr {...}
public record NegExpr(Expr e)           implements Expr {...}

The combination of sealed classes and records is sometimes referred to as algebraic data types: Records allow us to express product types, and sealed classes allow us to express sum types.

密封类和记录的组合有时被称为代数数据类型:记录允许我们表达product类型,密封类允许我们表达sum类型

Sealed classes in the JDK

An example of how sealed classes might be used in the JDK is in the java.lang.constant package that models descriptors for JVM entities:

JDK中的密封类

在JDK中如何使用密封类的一个例子是在java.lang.constant包中,它为JVM实体的描述符进行建模:

package java.lang.constant;

public sealed interface ConstantDesc
    permits String, Integer, Float, Long, Double,
            ClassDesc, MethodTypeDesc, DynamicConstantDesc {...}

// ClassDesc is designed for subclassing by JDK classes only
public sealed interface ClassDesc extends ConstantDesc
    permits PrimitiveClassDescImpl, ReferenceClassDescImpl {...}
final class PrimitiveClassDescImpl implements ClassDesc {...}
final class ReferenceClassDescImpl implements ClassDesc {...} 

// MethodTypeDesc is designed for subclassing by JDK classes only
public sealed interface MethodTypeDesc extends ConstantDesc
    permits MethodTypeDescImpl {...}
final class MethodTypeDescImpl implements MethodTypeDesc {...}

// DynamicConstantDesc is designed for subclassing by user code
public non-sealed abstract class DynamicConstantDesc implements ConstantDesc {...}
package java.lang.constant;

public sealed interface ConstantDesc
    permits String, Integer, Float, Long, Double,
            ClassDesc, MethodTypeDesc, DynamicConstantDesc {...}

// ClassDesc设计用于仅通过JDK的类进行子类化
public sealed interface ClassDesc extends ConstantDesc
    permits PrimitiveClassDescImpl, ReferenceClassDescImpl {...}
final class PrimitiveClassDescImpl implements ClassDesc {...}
final class ReferenceClassDescImpl implements ClassDesc {...} 

// MethodTypeDesc设计用于仅通过JDK的类进行子类化
public sealed interface MethodTypeDesc extends ConstantDesc
    permits MethodTypeDescImpl {...}
final class MethodTypeDescImpl implements MethodTypeDesc {...}

// DynamicConstantDesc设计用于通过用户代码进行子类化
public non-sealed abstract class DynamicConstantDesc implements ConstantDesc {...}

Java Grammar

NormalClassDeclaration:
  {ClassModifier} class TypeIdentifier [TypeParameters]
    [Superclass] [Superinterfaces] [PermittedSubclasses] ClassBody

ClassModifier:
  (one of)
  Annotation public protected private
  abstract static sealed final non-sealed strictfp

PermittedSubclasses:
  permits ClassTypeList

ClassTypeList:
  ClassType {, ClassType}

Java语法

普通类声明:
  {类修饰符} class 类型标识符 [类型参数]
    [父类] [父接口] [允许的子类] 类体

类修饰符:
  (其中之一)
  Annotation public protected private
  abstract static sealed final non-sealed strictfp

允许的子类:
  permits 类类型列表

类类型列表:
  类类型 {, 类类型}

JVM support for sealed classes

The Java Virtual Machine recognizes sealed classes and interfaces at runtime, and prevents extension by unauthorized subclasses and subinterfaces.

JVM对密封类的支持

Java虚拟机在运行时识别sealed类和接口,并防止未经授权的子类和子接口进行扩展。

Although sealed is a class modifier, there is no ACC_SEALED flag in the ClassFile structure. Instead, the class file of a sealed class has a PermittedSubclasses attribute which implicitly indicates the sealed modifier and explicitly specifies the permitted subclasses:

尽管sealed是一个类修饰符,但ClassFile结构中没有ACC_SEALED标志。相反,密封类的class文件具有PermittedSubclasses属性,该属性隐式指示sealed修饰符并显式指定允许的子类:

PermittedSubclasses_attribute {
    u2 attribute_name_index;
    u4 attribute_length;
    u2 number_of_classes;
    u2 classes[number_of_classes];
}
PermittedSubclasses_attribute {
    u2 attribute_name_index;
    u4 attribute_length;
    u2 number_of_classes;
    u2 classes[number_of_classes];
}

The list of permitted subclasses is mandatory—even when the permitted subclasses are inferred by the compiler, those inferred subclasses are explicitly included in the PermittedSubclasses attribute.

允许的子类列表是强制性的——即使编译器推断出允许的子类,这些推断的子类也明确包含在PermittedSubclasses属性中。

The class file of a permitted subclass carries no new attributes.

允许的子类的class文件没有新属性。

When the JVM attempts to defines a class whose superclass or superinterface has a PermittedSubclasses attribute, the class being defined must be named by the attribute. Otherwise, an IncompatibleClassChangeError is thrown.

当JVM尝试定义其父类或父接口具有PermittedSubclasses属性的类时,所定义的类必须由该属性命名。否则,将引发IncompatibleClassChangeError

Reflection API

The following public methods will be added to java.lang.Class:

  • java.lang.constant.ClassDesc[] getPermittedSubclasses()
  • boolean isSealed()

反射API

下面的public方法将被添加到java.lang.Class中:

  • java.lang.constant.ClassDesc[] getPermittedSubclasses()
  • boolean isSealed()

The method getPermittedSubclasses() returns an array containing java.lang.constant.ClassDesc objects representing all the permitted subclasses of the class if it is sealed, and returns an empty array if the class is not sealed.

方法getPermittedSubclasses()返回一个包含java.lang.constant.ClassDesc对象的数组,如果该类是密封的,则表示该类的所有允许的子类;如果该类未密封,则返回一个空数组。

The method isSealed returns true if the given class or interface is sealed. (Compare with isEnum.)

如果给定的类或接口是密封的,则方法isSealed返回true。(就像isEnum。)

Alternatives

Some languages have direct support for algebraic data types (ADTs), such as Haskell's data feature. It would be possible to express ADTs more directly and in a manner familiar to Java developers through a variant of the enum feature, where a sum of products could be defined in a single declaration. However, this would not support all the desired use cases, such as those where sums range over classes in more than one compilation unit, or sums that range over classes that are not products.

备选方案

某些语言直接支持代数数据类型(ADT),例如Haskell的data特性。通过enum特性的变体,可以更直接地以Java开发人员熟悉的方式表达ADT,其中可以在单个声明中定义sum和product。但是,这不会支持所有所需的用例,例如sum范围跨越多个编译单元中的类,或者sum范围跨越非product类的那些用例。

The permits clause allows a sealed class, such as the Shape class shown earlier, to be accessible-for-invocation by code in any module, but accessible-for-implementation by code in only the same module as the sealed class (or same package if in the unnamed module). This makes the type system more expressive than the access control system. With access control alone, if Shape is accessible-for-invocation by code in any module (because its package is exported), then Shape is also accessible-for-implementation in any module; and if Shape is not accessible-for-implementation in any other module, then Shape is also not accessible-for-invocation in any other module.

permits子句允许密封类,例如前面显示的Shape类,可以由任何模块中的代码访问以进行调用,但只能由与密封类(或相同包,如果在未命名的模块中)。这使得类型系统比访问控制系统更具表现力。单独使用访问控制,如果Shape可以被任何模块中的代码访问以调用(因为它的包被导出),那么Shape在任何模块中也可以被访问以实现;如果Shape在任何其他模块中不可访问以进行实现,那么Shape在任何其他模块中也不可访问以进行调用。

Dependencies

Sealed classes do not depend on records (JEP 384) or pattern matching (JEP 375), but they work well with both.

依赖

密封类不依赖于记录 (JEP 384) 或模式匹配 (JEP 375),但它们可以很好地与两者配合使用。