Java – how do I associate a string with each member of an enumeration?

Suppose I have some enumerations as follows:

enum Towns { Rome,Napoli,Modena }

I want to associate a string with each enumeration member Ideally, the string should be a description I want to make sure every town has a description:

Rome - Beautiful
Napoli - Good pizza
Modena - Ferrari store

If a city has no description, I also want to give it a compile time error

Solution

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

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

    public String getDesc() {
        return desc;
    }
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>