gpt4 book ai didi

java - 为什么不能从枚举构造函数调用 super 构造函数?

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:09:51 24 4
gpt4 key购买 nike

public enum A {
A(1);

private A(int i){
}

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

}

这里是 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());

最佳答案

枚举在编译器和运行时级别暗示了很多魔法,以保证 == 比较总是有效:

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 8.9节

没有无参数的 Enum() 构造函数,只有 Enum(String name, int ordinal)。但是允许用错误的参数调用那个显然会造成麻烦。

关于java - 为什么不能从枚举构造函数调用 super 构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4525073/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com