在java中,枚举声明如下:
enum Fruits{
BANANA,
ORANGE,
APPLE
}
在本例中,声明的枚举与类的类型相同。因此,当我创建枚举水果的实例时:
Fruits example = Fruits.ORANGE
这意味着创建了枚举水果的一个实例,然后为每个枚举创建实例。假设水果中的每个枚举都是水果的类型,它们会继续创建更多的实例……以此类推,导致无限递归。我是不是漏掉了什么?
发布于 2019-06-19 00:28:57
enum Fruits{
BANANA,
ORANGE,
APPLE
}
实际上等同于
class Fruits{
static final Fruits BANANA = new Fruits("BANANA", 0);
static final Fruits ORANGE = new Fruits("ORANGE", 1);
static final Fruits APPLE = new Fruits("APPLE", 2);
private Fruits(String name, int ordinal) {
super(name, ordinal);
}
}
再加点帮手的东西。尝试反编译一个枚举类(例如,使用javap
),你可以看到它是这样的。
因此,当你写下:
Fruits example = Fruits.ORANGE
您并不是在创建类的新实例:您只是引用了一个静态字段。
发布于 2019-06-19 02:20:56
但请记住,因为它们是单例,所以更改一个类型字段的属性会更改该字段的所有“实例”。
enum Fruit {
APPLE, ORANGE;
private String color = "red";
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
}
Fruit apple = Fruit.APPLE;
Fruit otherApple = Fruit.APPLE;
System.out.println(apple.getColor()); // prints red
System.out.println(otherApple.getColor()); // prints red
apple.setColor("green"); // change apples color
System.out.println(pple.getColor()); // prints green
System.out.println(otherApple.getColor()); // prints green
https://stackoverflow.com/questions/56658600
复制