枚举类:类的对象只有有限个,确定的.
当定义一组常量是,建议使用枚举类
定义枚举类: 方式一:自定义枚举类
单例模式视作只有一个的枚举类
public class Test { public static void main(String[] args) { System.out.println(Season.SPRING); } } //自定义枚举类 class Season{ //设置常量属性 private final String Season_Name; private final String Season_Desc; //私有化构造器 private Season(String seasonName,String seasonDesc) { this.Season_Name=seasonName; this.Season_Desc=seasonDesc; } //自定义常量 public static final Season SPRING =new Season("春天", "气候宜人"); public static final Season SUMER =new Season("夏天", "气候宜人"); public static final Season ATUMN =new Season("秋天", "气候宜人"); public static final Season WINTER =new Season("冬天", "气候宜人"); @Override public String toString() { return "Season [Season_Name=" + Season_Name + ", Season_Desc=" + Season_Desc + "]"; } //私有fianl属性不允许改变赋值,故只有get方法 public String getSeason_Name() { return Season_Name; } public String getSeason_Desc() { return Season_Desc; } }
方式二:使用enum关键字定义.-----jdk5.0新特性
//enum定义枚举类 enum Season{ //在类的内部首行创建类的对象,多个对象使用,隔开 SPRING("春天", "气候宜人"), SUMER("夏天", "气候宜人"), ATUMN("秋天", "气候宜人"), WINTER("冬天", "气候宜人"); //设置常量属性默认权限private fianl private final String Season_Name; private final String Season_Desc; //私有化构造器 private Season(String seasonName,String seasonDesc) { this.Season_Name=seasonName; this.Season_Desc=seasonDesc; } @Override public String toString() { return "Season [Season_Name=" + Season_Name + ", Season_Desc=" + Season_Desc + "]"; } //私有fianl属性不允许改变赋值,故只有get方法 public String getSeason_Name() { return Season_Name; } public String getSeason_Desc() { return Season_Desc; } }
枚举类中的常用方法(针对方式二):
---->>>values
---->>>valueOf
---->>>toString
/*System.out.println(Season.SPRING.getSeason_Name());*/ //values():返回当前枚举类所有对象构成的数组 Season[] season= Season.values(); for (int i = 0; i < season.length; i++) { System.out.println(season[i]); } System.out.println("*********************"); //valuesof(String object):查找返回指定名字的枚举类对象 Season season2 =Season.valueOf("WINTER"); System.out.println(season2); System.out.println("*********************"); //toString方法:如果自定义的枚举类没有toString方法,则默认继承enum当中的toString方法 System.out.println(Season.SPRING.toString());
枚举类实现接口(针对方式二):
枚举类的每一个对象都实现接口
SPRING("春天", "气候宜人"){ public void show(){ System.out.println("这是春天的气息"); } }, SUMER("夏天", "气候宜人"){ public void show(){ System.out.println("这是夏天的气息"); } }, ATUMN("秋天", "气候宜人"){ public void show(){ System.out.println("这是秋天的气息"); } }, WINTER("冬天", "气候宜人"){ public void show(){ System.out.println("这是冬天的气息"); } };