Java 的默认访问修饰符是否曾经是 public

Did Java's default access modifier used to be public

早在 2004 年,当我在 RIT 学习 CS 课程时,我的教授非常强调我们要记得输入访问修饰符。没有它,默认访问权限将是 public,我记得教授是这么说的。可能是我记错了,教授并没有说,但是现在显然不是这样了。我想知道在某个时候是否曾经是这种情况,也许 Sun 在某个时候改变了它 post-2004?

在 类 上,默认访问是程序包私有的。在接口上,成员的默认值是 public,而接口本身的默认值,如 类,是包私有的。

自 Java 发布以来它没有改变。

自启动以来,class 的默认访问说明符是包私有的。来自 Java docs:

If a class has no modifier (the default, also known as package-private), it is visible only within its own package (packages are named groups of related classes — you will learn about them in a later lesson.)

At the member level, you can also use the public modifier or no modifier (package-private) just as with top-level classes, and with the same meaning. For members, there are two additional access modifiers: private and protected. The private modifier specifies that the member can only be accessed in its own class. The protected modifier specifies that the member can only be accessed within its own package (as with package-private) and, in addition, by a subclass of its class in another package.

Java class自 Java 1.0.

以来,没有访问修饰符的 es 一直是包私有的

这是 JLS 1.0 的适用部分的 link:

If a class or interface type is declared public, then it may be accessed by any Java code that can access the package in which it is declared. If a class or interface type is not declared public, then it may be accessed only from within the package in which it is declared.

对于类型内部的成员,它表示:

A member (field or method) of a reference (class, interface, or array) type or a constructor of a class type is accessible only if the type is accessible and the member or constructor is declared to permit access:

  • If the member or constructor is declared public, then access is permitted. All members of interfaces are implicitly public.
  • Otherwise, if the member or constructor is declared protected, then access is permitted only when one of the following is true:

    • Access to the member or constructor occurs from within the package containing the class in which the protected member is declared.
    • Access occurs within a subclass of the class in which the protected member is declared, and the access is correct as described in §6.6.2.
  • Otherwise, if the member or constructor is declared private, then access is permitted only when it occurs from within the class in which it is declared.

  • Otherwise, we say there is default access, which is permitted only when the access occurs from within the package in which the type is declared.

这意味着如果没有修饰符,class 的 member/constructor 将是包私有的,而不是 public。

不过,接口的成员永远都是 public,因此对它们应用访问修饰符不会改变任何事情(好吧,如果你尝试 privateprotected 你会得到一个编译错误),所以无论你记得教授怎么说,它都不适用于接口。