Why can't enum constructors be protected or public in Java?

匿名 (未验证) 提交于 2019-12-03 03:10:03

问题:

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.

回答1:

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.



回答2:

Because you cannot call the constructor yourself.

Here is what the tutorials on Enums has to say:

Note: The constructor for an enum type must be package-private or private access. It automatically creates the constants that are defined at the beginning of the enum body. You cannot invoke an enum constructor yourself.



回答3:

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.



回答4:

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.



回答5:

if you want to declare enum public then save the enum file with the name of the enum.

Suppose you make an enum Book{} then save it by Book.java and make a seperate file for class

this is the only way to declare enum public.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!