Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't enum constructors be protected or public 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 gives me a compiler error if given the public or protected modifiers.

like image 339
Bad Request Avatar asked Sep 08 '10 01:09

Bad Request


People also ask

Can enum constructor be public?

The enum constructor must be private . You cannot use public or protected constructors for a Java enum . If you do not specify an access modifier the enum constructor it will be implicitly private .

Why are enum constructors private?

We need the enum constructor to be private because enums define a finite set of values (SMALL, MEDIUM, LARGE). If the constructor was public, people could potentially create more value. (for example, invalid/undeclared values such as ANYSIZE, YOURSIZE, etc.). Enum in Java contains fixed constant values.

Can enum have private constructor Java?

Now, you know that Enum can have a constructor in Java that can be used to pass data to Enum constants, just like we passed action here. Though Enum constructor cannot be protected or public, it can either have private or default modifier only.

Can enum be public in Java?

An enum can, just like a class , have attributes and methods. The only difference is that enum constants are public , static and final (unchangeable - cannot be overridden). An enum cannot be used to create objects, and it cannot extend other classes (but it can implement interfaces).


2 Answers

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.

like image 80
jjnguy Avatar answered Oct 06 '22 06:10

jjnguy


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.

like image 33
Cristian Sanchez Avatar answered Oct 06 '22 06:10

Cristian Sanchez