枚举的含义

一、什么叫枚举?

在生活中,其实就是列举的意思。在程序中,就是在一个类中列举出,列举出所有的常量,每一个常量都是一个实例。

二、枚举有什么用?

通常用来限定取值范围,所有内容只能从取值范围中获取,比如性别只有男和女,其他值都是不合法的。

三、举例

实际开发场景中,枚举类通常用来定义错误码、交易码等

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 static String getName(int index) {  
        for (Color c : Color.values()) {  
            if (c.getIndex() == index) {  
                return c.name;  
            }  
        }  
        return null;  
    }  
    // get set 方法  
    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;  
    }  
}  

获取枚举值的方法:Color.RED.getName();

猜你喜欢

转载自www.cnblogs.com/codeXi/p/12951258.html
今日推荐