Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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.

like image 749
Oleg Vazhnev Avatar asked Nov 09 '11 10:11

Oleg Vazhnev


2 Answers

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

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

    public String getDesc() {
        return desc;
    }
}
like image 82
flash Avatar answered Sep 21 '22 14:09

flash


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/

like image 37
Ravi Bhatt Avatar answered Sep 21 '22 14:09

Ravi Bhatt