Search code examples
javareflectionenumerationsuperclass

Why can't the super constructor be invoked from an enum constructor?


public enum A {
     A(1);

     private A(int i){
     }

     private A(){
         super(); // compile - error
             // Cannot invoke super constructor from enum constructor A()
     }

}

and here is the hierarchy of enum A extends from abstract java.lang.Enum extends java.lang.Object

Class c = Class.forName("/*path*/.A");
System.out.println(c.getSuperclass().getName());
System.out.println(Modifier.toString(c.getSuperclass().getModifiers()).contains("abstract"));
System.out.println(c.getSuperclass().getSuperclass().getName());

Solution

  • Enums imply a lot of magic at the compiler and runtime level to guaranty that == comparisons will always work:

    It is a compile-time error to attempt to explicitly instantiate an enum type (§15.9.1). The final clone method in Enum ensures that enum constants can never be cloned, and the special treatment by the serialization mechanism ensures that duplicate instances are never created as a result of deserialization. Reflective instantiation of enum types is prohibited. Together, these four things ensure that no instances of an enum type exist beyond those defined by the enum constants.

    Java Language Specification section 8.9

    There is no parameterless Enum() constructor, only Enum(String name, int ordinal). But allowing to call that one with wrong parameters would obviously cause trouble.