为什么枚举不会导致无限递归?

时间:2019-06-19 00:24:34

标签: java enums

在Java中,枚举声明如下:

enum Fruits{
BANANA,
ORANGE,
APPLE
}

在示例中,声明的枚举与类具有相同的类型。因此,当我创建枚举Fruits的实例时:

Fruits example = Fruits.ORANGE

这意味着创建了一个枚举水果的实例,然后继续为每个枚举创建实例。鉴于水果中的每个枚举都是水果类型,它们会继续创建更多实例...依此类推,导致无限递归。我想念什么吗?

2 个答案:

答案 0 :(得分:6)

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

您不是在创建类的新实例:您只是在引用静态字段。

答案 1 :(得分:0)

但是请记住,由于它们是单例,因此更改一种类型字段的属性会更改该字段的所有“实例”。

    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

相关问题