ABC123
ABC123

Reputation: 133

Why don't enums result in infinite recursions?

In java enums are declared as follows:

enum Fruits{
BANANA,
ORANGE,
APPLE
}

In the example, the enums declared are of the same type as the class. So, when I create an instance of the enum Fruits:

Fruits example = Fruits.ORANGE

it means that an instance of the enum fruits is created which then goes on to create instances for each enum. Given that each enum in fruits is of the type fruits they go on to create further instances... and so on resulting in infinte recursion. Am I missing something ?

Upvotes: 0

Views: 70

Answers (2)

WJS
WJS

Reputation: 40062

But remember that as they are singletons, changing attributes of one type field changes all "instances" of that field.

    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

Upvotes: 0

Andy Turner
Andy Turner

Reputation: 140484

enum Fruits{
BANANA,
ORANGE,
APPLE
}

is effectively the same as

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);
  }
}

with a little bit of extra helper stuff. Try decompiling an enum class (e.g. with javap) and you can see that it's like this.

As such, when you write:

Fruits example = Fruits.ORANGE

you're not creating a new instance of the class: you're just referring to a static field.

Upvotes: 6

Related Questions