Why does casting an enum to any interface not cause a compilation error in Java when the enum type contains at least one "extended" enum?

huangapple go评论68阅读模式
英文:

Why does casting an enum to any interface not cause a compilation error in Java when the enum type contains at least one "extended" enum?

问题

以下是您要求的翻译内容:

以下代码可以编译:

public enum Foo {
    A,
    B{};
    public static void main(String[] args) {
        Foo f = Foo.A;
        List s = (List)f;
    }
}

而这段代码则不能:

public enum Foo {
    A,
    B;
    public static void main(String[] args) {
        Foo f = Foo.A;
        List s = (List)f;
    }
}

我还可以用 Foo.A 替换 Foo.B 并得到相同的结果。
这里发生了什么?在第一个示例中,Foo.A 如何成为一个 List

英文:

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?

答案1

得分: 3

针对这种类型的转换,《缩窄引用转换规范》定义了规则。枚举类型没有特殊情况,只有对于final和非final类的区分。

基本枚举属于“final类”类别,但您的扩展枚举不属于该类别,因为它通过{}语法引入了一个子类。

当然,即使是在扩展枚举中,您的枚举常量也无法实现List接口,但是当前的规范简单地没有涵盖那种情况。

规范的未来修订可能会改进这一点,届时我希望编译器会实施额外的检查。但是现在,这种编译时的安全性还不可用。

英文:

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.

huangapple
  • 本文由 发表于 2020年10月14日 22:32:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/64355590.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定