问题描述
这段代码:
public class Sandbox {
public enum E {
VALUE {
@Override
public String toString() {
return "I'm the value";
}
};
@Override
public String toString() {
return "I'm the enum";
}
}
public static void main(String[] args) {
System.out.println(E.VALUE);
}
}
打印:
但是,这段代码:
public class Sandbox {
public static final class C {
@Override
public String toString() {
return "I'm a C";
}
}
public static void main(String[] args) {
System.out.println(new C() {
@Override
public String toString() {
return "I'm anonymous";
}
});
}
}
导致编译错误:
cannot inherit from final HelloWorld.C
为什么可以 E.VALUE
创建我看起来是一个匿名的 E
子类,覆盖 toString
方法,而使用最终类而不是隐式最终枚举会引发编译时错误?
Why can E.VALUE
create what appears to me to be an anonymous E
subclass, overriding the toString
method, while using a final class instead of an implicitly final enum throws a compile-time error?
更多具体来说,为什么可以 VALUE
覆盖 E
中的任何内容?我的印象是代码
More specifically, why can VALUE
override anything in E
? I was under the impression that the code
public enum E {
VALUE;
}
大致相当于
public static final class E {
public static final E VALUE = new E();
}
在这种情况下,不允许匿名性质。
in which case the anonymous nature would not be allowed.
有什么区别?为什么枚举是特别的?
What's the difference? Why are enums special?
推荐答案
根据:
Edit #2:Even though E
is not final
and is subclassed by VALUE
, explicitly trying to extend it such as with class Foo extends E
or enum Bar extends E
is a compile-time error according to 8.1.4. Superclasses and Subclasses:
这篇关于为什么我可以匿名地子类化枚举而不是最终的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!