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

JavaEnumsConstructor

Java Problem Overview


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.

Java Solutions


Solution 1 - Java

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.

Solution 2 - Java

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.

Solution 3 - Java

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.

Solution 4 - Java

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.

enum Color {
 RED, BLUE, YELLOW;
}

This will internally converted to:

public final class Color {
 private Color() {}
 public static final Color RED = new Color();
 public static final Color BLUE = new Color();
 public static final Color YELLOW = new Color();
}

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.

Solution 5 - Java

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBad RequestView Question on Stackoverflow
Solution 1 - JavajjnguyView Answer on Stackoverflow
Solution 2 - JavaCristian SanchezView Answer on Stackoverflow
Solution 3 - JavahartoView Answer on Stackoverflow
Solution 4 - JavaPraveen KishorView Answer on Stackoverflow
Solution 5 - JavaRahul PrajapatView Answer on Stackoverflow