为什么“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
的旧概念,这是一个常量集合?这就是原因吗
# 1 楼答案
TypeAndSize.Species.EMPTY
未使用成员字段。它可以访问TypeAndSize中定义的枚举类型Species type
正在定义一个成员字段,但它的类型不是enum,而是Species枚举与类和接口处于同一级别。这些是我们可以使用的积木类型。我们希望在整数常量上使用枚举的原因可以是elsewhere
希望这个链接能帮助你回答问题的第二部分
我已尽力澄清问题中使用的术语
# 2 楼答案
你所说的(
TypeAndSize.Species.EMPTY
)不是Spicies
的成员字段。当我们谈论“成员字段”时,它通常意味着实例变量(对于实例变量,也可以在Java中用enum
编写)在您所问的方面,您可以简单地将enum解释为使用类常量编写特殊类的特殊缩写:
类似于
(enum和手工制作的类之间仍然有很大区别,但它们还不是您所关心的问题)