gpt4 book ai didi

java - 枚举,静态方法和实现接口(interface)方法有什么用?

转载 作者:行者123 更新时间:2023-12-02 05:03:57 24 4
gpt4 key购买 nike

我对Enums有一些小疑问。我有以下困惑:-

  1. 枚举中的静态方法有何用途?我们大多数情况下使用Enums来声明常量。这个功能有什么用?
  2. 我明白了,Enum 可以实现接口(interface)。会有什么用呢?我只是对实际生活中的使用感到困惑。
  3. 另一个令人困惑的是,请参阅下面的代码片段,

    enum Position {
    FIRST, SECOND, THIRD;
    public static void main(String[] args) { //line 1
    Position p = Position.SECOND; //line 2
    switch(Position.THIRD) { //line 3
    case FIRST: //line 4
    System.out.println("Congrats, You are the winner");//line 5
    break; //line 6
    case SECOND : //line 7
    System.out.println("Congrats, You are the runner");//line 8
    break; //line 9
    default : //line 10
    System.out.println("Better luck next time"); //line 11
    }
    }
    }

    如果在 case 语句中使用,例如 Position。首先,它给出了编译时错误。我了解 JLS 不允许这样做。原因是使用类格式编写,无法进行符号链接(symbolic link)。但反过来也是如此。就像第 3 行一样,我使用带有完全限定名称的 enum 本身。所以,我的观点是,符号链接(symbolic link)的含义是什么以及为什么也允许第 3 行?

注意这基本上是一个打字错误。我的主要问题是,我们在 switch 条件下使用语法 Position.THIRD (编译器允许),但是当我们使用相同的语法以防万一时,这是不允许的。这是为什么?

引自 JLS

(One reason for requiring inlining of constants is that switch statements require constants on each case, and no two such constant values may be the same. The compiler checks for duplicate constant values in a switch statement at compile time; the class file format does not do symbolic linkage of case values.)

这里提到了符号链接(symbolic link)。但是,当我在 switch 条件 switch(Position.THIRD) 中编写类似的内容时,它在 CASE 语句中是被允许的。

最佳答案

What is the use of static methods in Enums?

与任何其他类型相同。对于枚举,它们通常是“给定这个字符串值,返回等效的枚举”或类似的东西。 (在 valueOf 不合适的情况下,例如存在多种表示形式的情况。)

I see, an Enum can implement an interface. What would be the use?

与任何接口(interface)相同 - 将实现与使用分离。例如,我之前已经让枚举实现了本地化相关的接口(interface)。

My main question was, we are using syntax Position.THIRD in switch condition(which is allowed by compiler) but when we use same syntax in case, it is not allowed. Why is that?

这只是一个语言决定 - 枚举类型必须与开关值本身的类型相同,因此它是冗余信息。与您引用的JLS部分无关。

关于java - 枚举,静态方法和实现接口(interface)方法有什么用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27981693/

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