user5457243
user5457243

Reputation:

enum passing multiple field values?

I've been starting to read about enums, and a wrote a small test class just to try it out:

public enum EnumTest{
  ITEMONE ("The 1st option"),
  ITEMTWO ("The 2nd option"),
  ITEMTHREE ("The 3rd option");

  EnumTest(String s){
    System.out.println(s);
  }
}

It should print "The 1st option" when I set it to ITEMONE, "The 2nd option" when I set it to ITEMTWO, etc., right? Instead, it's printing all of them:

EnumTest e = EnumTest.ITEMONE;

prints

The 1st option
The 2nd option
The 3rd option

What's going on?

Upvotes: 1

Views: 84

Answers (2)

cadrian
cadrian

Reputation: 7376

The enum creates all its values at load time. So when you first use it, all three values are created - hence the three messages.

Note that you can achieve the same result just loading the class (Class.forName()).

EDIT. If you want to only print one value, don't do it in the constructor.

public enum EnumTest{
  ITEMONE ("The 1st option"),
  ITEMTWO ("The 2nd option"),
  ITEMTHREE ("The 3rd option");

  private final String string;

  EnumTest(String s){
    string = s;
  }

  public String getString() {
    return string;
  }
}

Upvotes: 1

QBrute
QBrute

Reputation: 4535

Enums are created statically once the class is loaded. Since the print statement is inside the constructor, you will see all messages printed, because all enum constants are created.

If you want to see only one specific message, you could try it like this:

public enum EnumTest{
    ITEMONE ("The 1st option"),
    ITEMTWO ("The 2nd option"),
    ITEMTHREE ("The 3rd option");

    private final String message;

    EnumTest(String s){
        this.message = s;
    }

    public String getMessage() {
        return message;
    }
}

and then in your main:

System.out.println(EnumTest.ITEMONE.getMessage());

or alternatively

EnumTest e = EnumTest.ITEMONE;
System.out.println(e.getMessage());

Upvotes: 1

Related Questions