Oleg Vazhnev
Oleg Vazhnev

Reputation: 24057

How can I associate a string with each member of an enum?

Assume I have some enum like the following:

enum Towns { Rome, Napoli, Modena }

I want to associate a string for each enum member. Ideally, the string should be a description. I want to make sure that each town has a description:

Rome - Beautiful
Napoli - Good pizza
Modena - Ferrari store

I would also like to have it give me a compile time error if some town doesn't have a description.

Upvotes: 14

Views: 7899

Answers (2)

Ravi Bhatt
Ravi Bhatt

Reputation: 3163

enum Towns {
   Rome("Rome-beautiful");
   //add other enum types here too

   private String desc;
   Towns(String desc) 
   {
      this.desc=desc;
   }

   public String getDesc() 
   {
      return desc;
   }
}

Enums are treated as classes. You can write a constructor, have member variables and functions. The beauty is, constructor is called for each enum type and state is maintained for each type/

Upvotes: 4

flash
flash

Reputation: 6810

public enum Towns {
    Rome("rome")
    , Napoli("napoli")
    , Modena("modena");

    private String desc;
    Towns(String desc) {
        this.desc=desc;
    }

    public String getDesc() {
        return desc;
    }
}

Upvotes: 21

Related Questions