详细介绍java中的枚举类型.docVIP

  • 1
  • 0
  • 约2.75千字
  • 约 4页
  • 2017-02-08 发布于重庆
  • 举报
详细介绍java中的枚举类型

详细介绍java中的枚举类型 枚举类型是JDK5.0的新特征。Sun引进了一个全新的关键字enum来定义一个枚举类。下面就是一个典型枚举类型的定义: Java代码: public enum Color{ RED,BLUE,BLACK,YELLOW,GREEN } Color字节码代码 final enum hr.test.Color { // 所有的枚举值都是类静态常量 public static final enum hr.test.Color RED; public static final enum hr.test.Color BLUE; public static final enum hr.test.Color BLACK; public static final enum hr.test.Color YELLOW; public static final enum hr.test.Color GREEN; private static final synthetic hr.test.Color[] ENUM$VALUES; // 初始化过程,对枚举类的所有枚举值对象进行第一次初始化 static { 0 new hr.test.Color [1] 3 dup 4 ldc [16] //把枚举值字符串“RED”压入操作数栈 6 iconst_0 // 把整型值0压入操作数栈 7 invokespecial hr.test.Color(java.lang.String, int) [17] //调用Color类的私有构造器创建Color对象RED 10 putstatic hr.test.Color.RED : hr.test.Color [21] //将枚举对象赋给Color的静态常量RED。 。..。..。.. 枚举对象BLUE等与上同 102 return }; // 私有构造器,外部不可能动态创建一个枚举类对象(也就是不可能动态创建一个枚举值)。 private Color(java.lang.String arg0, int arg1){ // 调用父类Enum的受保护构造器创建一个枚举对象 3 invokespecial java.lang.Enum(java.lang.String, int) [38] }; public static hr.test.Color[] values(); // 实现Enum类的抽象方法 public static hr.test.Color valueOf(java.lang.String arg0); } 1、Color枚举类就是class,而且是一个不可以被继承的final类。 其枚举值(RED,BLUE.。.)都是Color类型的类静态常量, 我们可以通过下面的方式来得到Color枚举类的一个实例: Color c=Color.RED; 注意:这些枚举值都是public static final的,也就是我们经常所定义的常量方式,因此枚举类中的枚举值最好全部大写。 2、即然枚举类是class,当然在枚举类型中有构造器,方法和数据域。 但是,枚举类的构造器有很大的不同: (1) 构造器只是在构造枚举值的时候被调用。 Java代码: enum Color{ RED(255,0,0),BLUE(0,0,255),BLACK(0,0,0),YELLOW(255,255,0),GREEN(0,255,0); //构造枚举值,比如RED(255,0,0) private Color(int rv,int gv,int bv){ this.redValue=rv; this.greenValue=gv; this.blueValue=bv; } public String toString(){ //覆盖了父类Enum的toString() return super.toString()+“(”+redValue+“,”+greenValue+“,”+blueValue+“)”; } private int redValue; //自定义数据域,private为了封装。 private int greenValue; private int blueValue; } Java代码: public static void main(String args[]) { // Color colors=new Color(100,200,300); //wrong Color color=Co

文档评论(0)

1亿VIP精品文档

相关文档