java枚举类

来源:互联网 发布:什么是java远程调用 编辑:程序博客网 时间:2024/06/01 20:20

先简单介绍下枚举类和常量类的区别。

1.从表面看,常量类需要注释或者文档去支持。而且需要定义为public ststic final, 枚举类则不需要

2.从使用来看,常量类使用方便,创建简单。枚举类稍稍麻烦,但是因为稍稍麻烦,功能更加强大 还可以遍历访问。

3.常量类不能做性能优化(枚举类重写了equals方法,里面就是用==比较)。修改之后,引用的地方需要重新编译。常量定义为弱类型的时候,可以输入符合类型的任意值。

4.建议使用枚举类


下面是一个枚举类:

public enum RightTypePowerConstants {AdminPower("1", "系统管理员"),PresidentPower("2", "客户经理");private final String dictionaryCode;        private final String dictionaryRemarks;        private AppRightTypePowerConstants(String dictionaryCode, String dictionaryRemarks) {      this.dictionaryCode = dictionaryCode;      this.dictionaryRemarks = dictionaryRemarks;    }    public String getDictionaryCode() {    return dictionaryCode;    }        public String getValue() {    return dictionaryRemarks;    }        @Override    public String toString(){      return dictionaryCode+":"+dictionaryRemarks;    }        //使用    public static void main(String[] args) {    System.out.println(AppRightTypePowerConstants.PresidentPower.getDictionaryCode());    System.out.println(AppRightTypePowerConstants.PresidentPower.getValue());
for(AppRightTypePowerConstants a :AppRightTypePowerConstants.values()){    System.out.println(a.dictionaryCode+":"+a.dictionaryRemarks);    }}    }

枚举类可以实现接口。

还可以在接口中组织多个枚举类。