开发者

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

开发者 https://www.devze.com 2023-02-01 05:35 出处:网络
public enum A { A(1); private A(int i){ } private A(){ super(); // compile - error // Cannot invoke super constructor from enum constructor A()
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.prin开发者_如何学Gotln(c.getSuperclass().getName());
System.out.println(Modifier.toString(c.getSuperclass().getModifiers()).contains("abstract"));
System.out.println(c.getSuperclass().getSuperclass().getName());


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.


From the Java Tutorial on Enums:

All enums implicitly extend java.lang.Enum. Since Java does not support multiple inheritance, an enum cannot extend anything else.

You can't invoke the super() constructor because the compiler automatically inserts a hidden call to super(name, ordinal) into any constructor you define.


It is a fact that you cannot declare an enum as extending another class. Therefore, there is only one possible super constructor for an enum.

I guess, since since you can't chain to anything other than super() they decided that it wasn't worth allowing the use of super at all in an enum constructor.

Either way, you are not losing anything.


Because there is no super() constructor, see dogbane's answer, and because the compiler automatically inserts the super(...) call that is required, ditto.

Why is this a problem?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号