This code:
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);
}
}
prints:
I'm the value
However, this code:
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";
}
});
}
}
results in a compilation error:
cannot inherit from final HelloWorld.C
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?
More specifically, why can VALUE
override anything in E
? I was under the impression that the code
public enum E {
VALUE;
}
was roughly equivalent to
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?