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

Viewed 47945

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.

5 Answers

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.

Related