`
zhaolei415
  • 浏览: 166425 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

java枚举

阅读更多
4,java枚举
首先我们说为什么要用枚举(什么时候用它)?
答:让某个类型变量的取值只能为若干固定值中的一个否则编译器就会报错。
以前没有枚举类的时候我们咋办的了?
答:(1)私有的构造函数(2)每个元素用公有的静态成员变量表示并且调用私有构造函数
例子:
    final class Season
      {public static final Season SPRING=new Season();
        public static final Season WINTER=new Season();
        public static final Season SUMMER=new Season();
        public static final Season AUTUMN=new Season();
        private Season(){...}
      }


enum很像特殊的class,实际上enum声明定义的类型就是一个类。而这些类都是类库中Enum类的子类(java.lang.Enum<E>)。它们继承了这个Enum中的许多有用的方法
	public enum Color{   
	    RED,BLUE,BLACK,YELLOW,GREEN   
	}  

1、Color枚举类是特殊的class,其枚举值(RED,BLUE...)是Color的类对象(类实例):
                      Color c=Color.RED;
    而且这些枚举值都是public static final的,也就是我们经常所定义的常量方式,因此枚举类中的枚举值最好全部大写。
2、即然枚举类是class,当然在枚举类型中有构造器,方法和数据域。但是,枚举类的构造器有很大的不同:
      (1) 构造器只是在构造枚举值的时候被调用。
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(){  //自定义的public方法   
	                return super.toString()+"("+redValue+","+greenValue+","+blueValue+")";   
	                }   
	      
                       private int redValue;  //自定义数据域,private为了封装。   
	                private int greenValue;   
	                private int blueValue;   
	 }  

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

特别指出:如果枚举类中只有一个枚举值的话那么就和单例模式有异曲同工之妙了。
附件是一个文档是从百度文库中整出来的,本文参考了其中的内容。







0
1
分享到:
评论
2 楼 teacherzhu 2014-07-24  
http:/http://www.iteye.com/images/smiles/icon_wink.gif/www.iteye.com/ihttp:http://www.iteye.com/images/smiles/icon_arrow.gif//www.iteye.com/images/smiles/icon_rolleyes.gifmages/smiles/icon_cry.gihttp://www.iteye.com/images/smiles/icon_sad.giffhttp://www.iteye.com/images/http:/http://www.iteye.com/images/smiles/icon_idea.gif/www.iteye.com/images/smiles/icon_question.gifsmiles/icon_redface.gif
1 楼 happylouis 2013-09-02  
写的到位,明白

相关推荐

Global site tag (gtag.js) - Google Analytics