Java的默认访问修饰符曾经是公开的
作者:互联网
早在2004年,当我在RIT参加CS课程的介绍时,我的教授非常强调我们记得放入访问修饰语.没有它,默认访问将是公开的,我记得教授说的.也许我的记忆是错的,教授实际上并没有说出来,但显然现在情况并非如此.我想知道在某些时候是否曾经是这种情况,也许Sun在2004年之后的某些时候改变了它?
解决方法:
自Java 1.0以来,没有访问修饰符的Java类一直是包私有的.
以下是JLS 1.0适用部分的链接:
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.
这意味着如果没有修饰符,类的成员/构造函数将是包私有的,而不是公共的.
但是,接口的成员绝不是公共的,所以对它们应用访问修饰符不会改变一个东西(好吧,如果你尝试私有或受保护,你会得到一个编译错误),所以无论你怎么记得教授说,它不适用于接口.
标签:java,access-modifiers 来源: https://codeday.me/bug/20190724/1526998.html