枚举用来存放一些只存在几种情况的对象,例如:星期、颜色等。
若枚举只有一个成员,则可以作为一种单例模式的实现方式。 #1.自定义枚举类//自定义枚举类 class Season{ //2.定义两个属性 private final String seasonName; private final String seasonDesc; //1.私有构造器,防止外部调用 private Season(String seasonName,String seasonDesc){ this.seasonName = seasonName; this.seasonDesc = seasonDesc; } //3.创建枚举类的对象 public static final Season SPRING = new Season("春天", "春暖花开"); public static final Season SUMMER = new Season("夏天", "夏日炎炎"); public static final Season AUTUMN = new Season("秋天", "秋高气爽"); public static final Season WINTER = new Season("冬天", "千里冰封 "); public String getSeasonName() { return seasonName; } public String getSeasonDesc() { return seasonDesc; } @Override public String toString() { return "Season [seasonName=" + seasonName + ", seasonDesc=" + seasonDesc + "]"; }}
自定义枚举类的使用
public class TestSeason { public static void main(String[] args) { Season spring = Season.SPRING; System.out.println(spring); System.out.println(spring.getSeasonName()); }}
#2.enum
//使用enum枚举类 enum Season{ //1.列举出所有的类型 SPRING("春天", "春暖花开"), SUMMER("夏天", "夏日炎炎"), AUTUMN("秋天", "秋高气爽"), WINTER("冬天", "千里冰封 "); //2.定义两个属性 private final String seasonName; private final String seasonDesc; //3.私有构造器,防止外部调用 private Season(String seasonName,String seasonDesc){ this.seasonName = seasonName; this.seasonDesc = seasonDesc; } public String getSeasonName() { return seasonName; } public String getSeasonDesc() { return seasonDesc; } @Override public String toString() { return "Season [seasonName=" + seasonName + ", seasonDesc=" + seasonDesc + "]"; }}
使用方法
public static void main(String[] args) { //1.返回枚举类所有的对象 Season[] season = Season.values(); for (int i = 0; i < season.length; i++) { System.out.println(season[i]); } //2.单独使用一种情况 String tmp = Season.SPRING.getSeasonName(); System.out.println(tmp); }