如何使用java 枚举定义常量

2025-04-30 14:30:14
推荐回答(2个)
回答1:

枚举类:
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

回答2:

public enum Color {
RED, GREEN, BLANK, YELLOW
}