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.
public enum Towns {
Rome("rome")
, Napoli("napoli")
, Modena("modena");
private String desc;
Towns(String desc) {
this.desc=desc;
}
public String getDesc() {
return desc;
}
}
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With