Why can not be protected or published in Java?

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 it gives me a compiler error if public or protected modifiers are given.

+52
java enums constructor
Sep 08 2018-10-10T00:
source share
5 answers

Think of Enums as a class with a finite number of instances. There can never be any different instances next to those that you initially declare.

Thus, you cannot have an open or protected constructor, as this will allow you to create more instances.

Note: this is probably not an official reason. But for me it makes sense to reason about enums in this way.

+70
Sep 08 2018-10-10T00:
source share

Because you cannot call the constructor yourself.

Here's what the Enums tutorials should say:

Note. The constructor for the enumeration type must be closed or closed. It automatically creates the constants that are defined at the beginning of the enumeration body. You cannot call an enumeration constructor yourself.

+15
Sep 08 '10 at 1:52
source share

Enumerations contain a fixed set of values ​​that must be known at compile time. It makes no sense to create new literals at run time, which would be possible if the constructor was visible.

+6
Sep 08 2018-10-10T00:
source share

The key point to keep in mind is that enumerations that are not part of the class can only be declared using the public modifier or by default , just like a non-inner class.

0
May 26 '16 at 4:18
source share

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

Suppose you made enum Book{} , then save it to Book.java and make a separate file for the class

this is the only way to declare enum public.

-3
Jul 26 '11 at 10:19
source share



All Articles