一.枚举
枚举的来源:意思是枚举是为了解决一个类中仅有几个固定常量值二设计的.
在JDK1.5 之前,我们定义常量都是: public static fianl… 。现在好了,有了枚举,可以把相关的常量分组到一个枚举类型里,而且枚举提供了比常量更多的方法。
注意:
1.枚举的可以有构造方法,但是构造方法是私有的,不允许外部创建枚举实例.
2.每一个枚举的成员都是枚举类的对象实例,也只有这么多个实例.
3.枚举的成员底层是用 public static final修饰的.
public enum Season {
//这里的每一个成员其实都是枚举类的实例.因为构造方法私有化,所以代表Season枚举只会有四个对象.
//public static final SPRNG = new Season(new int[]{1,2,3},"春天");
SPRING(new int[]{1,2,3},"春天"),
SUMMER(new int[]{4,5,6},"夏天"),
AUTUMN(new int[]{7,8,9},"秋天"),
WINTER(new int[]{10,11,12},"冬天");
public int[] months;
public String desc;
//修饰符只能是private,默认也是private,因为enum枚举设计就是为了来存放常量的,所以不允许外部创建对象实例.
private Season(int[] months,String desc) {
this.months = months;
this.desc = desc;
}
}
//调用枚举类.
public class SeasonDemo {
public static void main(String[] args) {
Season se;
Season se2 = Season.SUMMER; //这里必须使用Season.SUMMER
switch (se2) {
case SPRING: //注意这里不能再使用Season.SPRING了
System.out.println("春天来了");
System.out.println(se2.desc);
break;
case SUMMER:
System.out.println("夏天来了");
System.out.println(se2.desc);
break;
case AUTUMN:
System.out.println("秋天来了");
System.out.println(se2.desc);
break;
case WINTER:
System.out.println("冬天来了");
System.out.println(se2.desc);
break;
}
}
}