public
or protected
modifiers are not allowed with enum
constructors. Why? I have tried reading the standard documentation but didn't understand it well.
Asked
Active
Viewed 405 times
1

lealceldeiro
- 14,342
- 6
- 49
- 80

Mukund
- 41
- 6
-
Loosely related: https://stackoverflow.com/questions/26618890/difference-between-java-enum-with-no-values-and-utility-class-with-private-const – DaveyDaveDave May 20 '19 at 09:59
-
Because it's inside the same `enum` where the values are defined, if you ideally could declare a constructor `public` (for example)... external APIs could (ideally) create new values for the enum..... and enum are supposed to be constant values. – lealceldeiro May 20 '19 at 09:59
-
1@lealceldeiro I think you are misusing the word 'ideally'. There is nothing ideal about it. Enums represent a finite set of values. The ability to add more is not desirable. It would break switch statements etc. – Michael May 20 '19 at 10:01
-
You should ask yourself why would you want to use an Enum? And would an Enum still be useful if you could just add values to it? – Stephan Hogenboom May 20 '19 at 10:01
-
This constructor have to be private, because enums define a finite set of values . If the constructor was public people could potentially create more values. This would extend the set of initially declared values. – arst3k May 20 '19 at 10:01
1 Answers
2
The constructor is meant to customize the creation of constants inside the enumeration once, not to create and initialize different instances of the enum (this doesn't make sense). This is why it must be private.
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.
Link: https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html

Hichem BOUSSETTA
- 1,791
- 1
- 21
- 27