为什么枚举可以有一个包私有构造函数? [英] Why can a enum have a package-private constructor?
问题描述
既然枚举构造函数只能由它的常量调用,为什么还允许它是包私有的?
Since an enum constructor can only be invoked by its constants, why is it then allowed to be package-private?
推荐答案
构造函数实际上不是包私有的......它是隐式private
接口方法隐式public<的方式/code> 即使您不添加关键字.
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.
JLS 的相关部分(§8.8.3) 声明:
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.
如果没有为枚举类型的构造函数指定访问修饰符,则构造函数为private
.
If no access modifier is specified for the constructor of an enum type, the constructor is private
.
如果枚举类型(第 8.9 节)的构造函数声明为 public
或 protected
,则会导致编译时错误.
It is a compile-time error if the constructor of an enum type (§8.9) is declared public
or protected
.
这篇关于为什么枚举可以有一个包私有构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!