Java 个子包在不提供特殊访问关系的情况下有什么作用?

What do Java subpackages do, given that they don't provide a special access relationship?

我在 Stack Overflow 和其他地方看到很多帖子断言 Java 没有子包的概念。经常指出的一件事是包与其“子包”之间没有任何特殊的访问关系。例如,无法将 class 或 com.example 中的方法暴露给 com.example.subpackage 中的 class es(反之亦然)而不将其暴露给所有其他包。然而,尽管有这些断言,我还是看到 Java Language Specification does in fact define the concept of "subpackage" in Chapter 7. Packages and Modules.

The members of a package are class and interface types, which are declared in compilation units of the package, and subpackages, which may contain compilation units and subpackages of their own.

因此,Java 中的子包是什​​么,它有什么作用?

存在子包以方便组织代码。它们对 class/interface 命名施加了限制(class 不能与子包具有相同的完全限定名称),但在其他方面与两个不相关的包没有区别。

Java 语言规范定义了第 7.1 节中的子包,Package Members

子包是直接嵌套在另一个包中的任何包。例如,com.example.subpackagecom.example:

的子包

The members of a package are its subpackages and all the top level class types and top level interface types declared in all the compilation units of the package.

For example, in the Java SE Platform API:

  • The package java has subpackages awt, applet, io, lang, net, and util, but no compilation units.
  • The package java.awt has a subpackage named image, as well as a number of compilation units containing declarations of class and interface types.

子包在子包和包内 classes/interfaces 之间实施命名约束。即,子包和 class/interface 不能在同一个包内共享相同的名称:

A package may not contain two members of the same name, or a compile-time error results.

Here are some examples:

  • Because the package java.awt has a subpackage image, it cannot (and does not) contain a declaration of a class or interface type named image.
  • If there is a package named mouse and a member type Button in that package (which then might be referred to as mouse.Button), then there cannot be any package with the fully qualified name mouse.Button or mouse.Button.Click.
  • If com.nighthacks.java.jag is the fully qualified name of a type, then there cannot be any package whose fully qualified name is either com.nighthacks.java.jag or com.nighthacks.java.jag.scrabble.

分包概念主要用于组织目的。对名称冲突的限制是语言赋予子包的意义:

The hierarchical naming structure for packages is intended to be convenient for organizing related packages in a conventional manner, but has no significance in itself other than the prohibition against a package having a subpackage with the same simple name as a top level type declared in that package.

For example, there is no special access relationship between a package named oliver and another package named oliver.twist, or between packages named evelyn.wood and evelyn.waugh. That is, the code in a package named oliver.twist has no better access to the types declared within package oliver than code in any other package.