zoukankan      html  css  js  c++  java
  • Java中enum的使用

    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;
     }

    1、Color枚举类就是class,而且是一个不可以被继承的final类。其枚举值(RED,BLUE...)都是Color类型的类静态常量, 我们可以通过下面的方式来得到Color枚举类的一个实例:
                                                             Color c=Color.RED; 
    注意:这些枚举值都是public static final的,也就是我们经常所定义的常量方式,因此枚举类中的枚举值最好全部大写。 

    2、即然枚举类是class,当然在枚举类型中有构造器,方法和数据域。但是,枚举类的构造器有很大的不同:

     (1) 构造器只是在构造枚举值的时候被调用。

      (2) 构造器只能私有private,绝对不允许有public构造器。 这样可以保证外部代码无法新构造枚举类的实例。这也是完全符合情理的,因为我们知道枚举值是public static final的常量而已。 但枚举类的方法和数据域可以允许外部访问。

      

    public static void main(String args[])
    {
            // Color colors=new Color(100,200,300);  //wrong
               Color color=Color.RED;
               System.out.println(color);  // 调用了toString()方法
    }   

    3、所有枚举类都继承了Enum的方法。 

    4、枚举类可以在switch语句中使用。

    Color color=Color.RED;
    switch(color){
            case RED: System.out.println("it's red");break;
            case BLUE: System.out.println("it's blue");break;
            case BLACK: System.out.println("it's blue");break;
    }
  • 相关阅读:
    C语言 assert
    Java6上开发WebService
    unity3d绘制贴图
    unity3d物理引擎
    unity3dVisual Studio Tools for Unity快捷键
    unity3d小案例之角色简单漫游
    unity3d射线(Ray)
    unity3d准备工作
    unity3d编辑器结构
    unity3d碰撞检测
  • 原文地址:https://www.cnblogs.com/aloe/p/2693818.html
Copyright © 2011-2022 走看看