Reputation: 384
The following code compiles:
public enum Foo {
A,
B{};
public static void main(String[] args) {
Foo f = Foo.A;
List s = (List)f;
}
}
This one doesn't:
public enum Foo {
A,
B;
public static void main(String[] args) {
Foo f = Foo.A;
List s = (List)f;
}
}
I could also replace Foo.A
with Foo.B
and get the same result.
What is going on here? How could Foo.A
ever be a List
in the first example?
Upvotes: 2
Views: 148
Reputation: 7290
For this type of casting, the spec on Narrowing Reference Conversion defines the rules. There is no special case for enums, only a distinction between final and non-final classes.
The basic enum falls into the "final class" category, but your extended enum doesn't, as it introduces a subclass via the {}
syntax.
Of course, even with the extended enum, there's no way that one of your enum constants could ever implement List
, but the current spec simply doesn't cover that situation.
A future revision of the spec might improve that, and then I'd expect compilers to implement the additional checks. But right now, that degree of compile-time safety isn't available.
Upvotes: 3