android培训java培训期待与您交流!  
枚举类和自动包装
     一、枚举
      枚举由不重复的常量构成,在java中使用enmu关键字定义枚举,所有的枚举会自动继承java.lang.enmu。
比如定义交通灯的枚举。
public enum TrafficLamp {
RED,GREED ,YELLOW;
}
使用枚举可以结合使用switch语句构造功能。
//定义一个 enum类,包含TrafficLamp的所有情况
 enum TrafficLamp {
           REDGREEDYELLOW;
}
 class TrafficDemo {
           //enmu经常和switch一起用
public void run(TrafficLamp light ){
           switch(light ){
           case RED :for(int count =40 ;count >0 ;count --)
                   System .out.println( "现在是:红灯" +count );
                    break;
           case GREED :for(int count =30 ;count >0 ;count --)
                   System .out.println( "现在是:绿灯" +count );
                    break;
           case YELLOW :for(int count =5 ;count >0 ;count --)
                   System .out.println( "现在是:黄灯" +count );
                    break;
           }
}
 
           public static void main (String[] args) {
                    // TODO Auto-generated method stub
TrafficDemo td=new TrafficDemo();
//调用RED状态
td.run (TrafficLamp.RED) ;
//调用TrafficDemo,循环一直转下去
while(true ){
           for ( TrafficLamp light:TrafficLamp .values())
          td .run (light) ;
}
           }
}
枚举可以在枚举类中选择带参数的构造方法,及带方法的枚举
import java.util.Random;
//java编程思想中的例子
//定义自动售货机
public enum Input {
NIKEL(5 )DIME(10 )QUATER(25 )DOLLAR(100 )TOOTHOASTE(200 )CHIPS(75 )SODA(100 )SIAO(50 ),
ABORT_TRABSACTION{
           public int amount(){
                    throw new RuntimeException("ABORT.amount()" );
           }},
           STOP{
                    public int amount(){
                              throw new RuntimeException("SHUT_DOWN.amount()" );
                    }
};
//定义属性
int value ;
Input(int value){this .value =value ;}
Input(){}
int amount(){ return value ;}
//定义方法
static Random rand =new Random();
public static Input randomselections(){
return values()[rand .nextInt (values().length -1 )]      
}
}
二、自动装箱
         由于Java是面对对象的,而基本数据类型不是对象。为了解决这个问题,java建立了包装类,将基本数据类型包装成对象。
包装类为封装基本数据类型提供了两种构造方法:
Integer a=new Integer (14) ;//数据类型也行
Integer b=new Integer ("14") ;//字符串形式也可以
    Java JDK1.5以后,包装类可以自动装箱,当你需要用对象的时候,编译器会自动帮你完成上面的过程,但是会有额外开销。
                    android培训java培训期待与您交流!  
 
posted on 2014-05-14 18:06  耍王在1218  阅读(156)  评论(0编辑  收藏  举报