如何使用java 枚举定义常量

 我来答
那年的雪景
2016-12-31 · TA获得超过633个赞
知道小有建树答主
回答量:347
采纳率:50%
帮助的人:217万
展开全部
枚举类:
public enum Color {
RED("红色", 1), GREEN("绿色", 2), BLANK("白色", 3), YELLO("黄色", 4);
    
    
    private String name ;
    private int index ;
     
    private Color( String name , int index ){
        this.name = name ;
        this.index = index ;
    }
     
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getIndex() {
        return index;
    }
    public void setIndex(int index) {
        this.index = index;
    }
}

测试类:
public class B {
 
    public static void main(String[] args) {
 
        //输出某一枚举的值
        System.out.println( Color.RED.getName() );
        System.out.println( Color.RED.getIndex() );
 
        //遍历所有的枚举
        for( Color color : Color.values()){
            System.out.println( color + "  name: " + color.getName() + "  index: " + color.getIndex() );
        }
    }
 
}

输出结果:
红色
1
RED  name: 红色  index: 1
GREEN  name: 绿色  index: 2
BLANK  name: 白色  index: 3
YELLO  name: 黄色  index: 4
匿名用户
2016-12-31
展开全部
public enum Color {
RED, GREEN, BLANK, YELLOW
}
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式