有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

为什么“enum”的实例字段在java中是“enum”?

对于下面的TypeAndSize

class TypeAndSize {

  Species type;               // runType EMPTY, SHARK, or FISH
  int size;                   // Number of cells in the run for that runType.

  enum Species{EMPTY,SHARK,FISH}

  /**
   *  Constructor for a TypeAndSize of specified species and run length.
   *  @param species is Ocean.EMPTY, Ocean.SHARK, or Ocean.FISH.
   *  @param runLength is the number of identical cells in this run.
   *  @return the newly constructed Critter.
   */

  TypeAndSize(Species species, int runLength) {
    if (species == null)    {   
      System.out.println("TypeAndSize Error:  Illegal species.");
      System.exit(1);
    }
    if (runLength < 1) {
      System.out.println("TypeAndSize Error:  runLength must be at least 1.");
      System.exit(1);
    }
    this.type = species;
    this.size = runLength;
  }

}

在下面的代码中使用enum类类型的成员字段

class RunLengthEncoding {
    ...
    public RunLengthEncoding(int i, int j, int starveTime) {
          this.list = new DList2();
          this.list.insertFront(TypeAndSize.Species.EMPTY, i*j);
          ....
      }
    ...
}

让我问这个问题

我的问题: 为什么enum类的成员字段被设计为enum的实例?因为传递enum类类型的参数很容易,它可以向后兼容C语言中的enum的旧概念,这是一个常量集合?这就是原因吗


共 (2) 个答案

  1. # 1 楼答案

    with the usage of member fields of enum class type

    TypeAndSize.Species.EMPTY未使用成员字段。它可以访问TypeAndSize中定义的枚举类型

    Species type正在定义一个成员字段,但它的类型不是enum,而是Species

    枚举与类和接口处于同一级别。这些是我们可以使用的积木类型。我们希望在整数常量上使用枚举的原因可以是elsewhere

    希望这个链接能帮助你回答问题的第二部分
    我已尽力澄清问题中使用的术语

  2. # 2 楼答案

    你所说的(TypeAndSize.Species.EMPTY)不是Spicies的成员字段。当我们谈论“成员字段”时,它通常意味着实例变量(对于实例变量,也可以在Java中用enum编写)

    在您所问的方面,您可以简单地将enum解释为使用类常量编写特殊类的特殊缩写:

    enum Foo {
      A,
      B;
    }
    

    类似于

    class Foo {
        public static final Foo A = new Foo();
        public static final Foo B = new Foo();
    
        private Foo() {}
    }
    

    (enum和手工制作的类之间仍然有很大区别,但它们还不是您所关心的问题)