为什么枚举有一个包私有构造函数? [英] Why can a enum have a package-private constructor?
问题描述
构造函数实际上不是package-private ...它隐式地是 private
接口方法隐式的方式 public
even如果你不添加关键字。
JLS的相关部分(§8.8.3)状态:
如果没有为普通类的构造函数指定访问修饰符,构造函数具有默认访问权限。
如果没有为枚举类型的构造函数指定访问修饰符,构造函数是
private
。
如果枚举类型的构造函数(§ 8.9)被声明为
public
或protected
。
Since an enum constructor can only be invoked by its constants, why is it then allowed to be package-private?
The constructor actually isn't package-private... it's implicitly private
the way interface methods are implicitly public
even if you don't add the keyword.
The relevant section of the JLS (§8.8.3) states:
If no access modifier is specified for the constructor of a normal class, the constructor has default access.
If no access modifier is specified for the constructor of an enum type, the constructor is
private
.It is a compile-time error if the constructor of an enum type (§8.9) is declared
public
orprotected
.
这篇关于为什么枚举有一个包私有构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!