java jDK1.5 之枚举

    技术2022-05-20  33

    作用:

    编译程序时,检测枚举值是否合法。

    限定值的范围。

     

    枚举相当于一个类,里面的元素相当于是该类的实例对象,默认调用toString方法打印。

     

    重要方法

    枚举名.valueOf("值")。把字符值转换成枚举对象。

    枚举名.values()转换成数组。

     

     

    枚举的构造方法:

    public enum Day{

         Sun(1),MON;

          private Day(){system.out.println("默认的构造函数");}

          private Day(int i){system.out.println("调用带参数的构造函数");}

    }

     

     

    复杂的枚举DEMO:

    class  EnumTest{ public static void main(String[] args)  {  TrafficLamp la=TrafficLamp.RED;  System.out.println(la.name()); }

     public enum TrafficLamp{    RED(30){//RED元素由以下子类(内部类)实现。   public TrafficLamp nextLamp(){    return GREEN;   }  },GREEN(45){   public TrafficLamp nextLamp(){    return YELLOW;   }  },YELLOW(5){   public TrafficLamp nextLamp(){    return RED;   }  };

      public abstract TrafficLamp nextLamp();

      private int time;  private TrafficLamp(int time){this.time=time;} }}

     


    最新回复(0)