为什么 Java 中的枚举构造函数不能被保护或公开?
整个问题都在标题中。例如:
enum enumTest {
TYPE1(4.5, "string1"), TYPE2(2.79, "string2");
double num;
String st;
enumTest(double num, String st) {
this.num = num;
this.st = st;
}
}
构造函数可以使用默认或 private
修饰符,但如果使用 public
或 protected
修饰符,则会出现编译器错误。
The whole question is in the title. For example:
enum enumTest {
TYPE1(4.5, "string1"), TYPE2(2.79, "string2");
double num;
String st;
enumTest(double num, String st) {
this.num = num;
this.st = st;
}
}
The constructor is fine with the default or private
modifier, but gives me a compiler error if given the public
or protected
modifiers.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
将枚举视为具有有限数量实例的类。除了您最初声明的实例之外,永远不会有任何不同的实例。
因此,您不能拥有公共或受保护的构造函数,因为这将允许创建更多实例。
注意:这可能不是官方原因。但对我来说,以这种方式思考枚举是最有意义的。
Think of Enums as a class with a finite number of instances. There can never be any different instances beside the ones you initially declare.
Thus, you cannot have a public or protected constructor, because that would allow more instances to be created.
Note: this is probably not the official reason. But it makes the most sense for me to think of
enums
this way.因为你不能自己调用构造函数。
以下是Enums 教程的内容:
Because you cannot call the constructor yourself.
Here is what the tutorials on Enums has to say:
枚举包含一组固定的值,这些值必须在编译时已知。在运行时创建新的文字是没有意义的,如果构造函数可见,则这是可能的。
Enums contain a fixed set of values, which must all be known at compile-time. It doesn't make sense to create new literals at run-time, which would be possible if the constructor were visible.
这是因为 Java 中的 enum 包含固定的常量值。因此,拥有公共或受保护的构造函数是没有意义的,因为您无法创建枚举实例。
另请注意,内部枚举会转换为类,如下所示。
这将在内部转换为:
因此,每个枚举常量都表示为枚举类型的对象。由于我们无法显式创建枚举对象,因此我们无法直接调用枚举构造函数。
This is because enum is Java contains fixed constant values. So, there is no point in having public or protected constructor as you cannot create instance of enum.
Also, note that internally enum is converted to class as below.
This will internally converted to:
So, every enum constant is represented as an object of type enum. As we can't create enum objects explicitly hence we can't invoke enum constructor directly.
要记住的关键点是,未包含在类中的枚举只能使用 public 或 default 修饰符进行声明,就像非内部类一样。
The key point to remember is that an enums that is not enclosed in a class can be declared with only the public or default modifier, just like a non-inner class.