1 //手动实现枚举类 2 //步骤 3 1.通过private将构造器隐藏起来 4 2.把这个类的所有可能的实例都使用public static final修饰的类变量来保存 5 3.如果有必要,可以提供一些静态方法,允许其他程序根据特定的参数来获取与之匹配的实例 6 public class Season{ 7 //把Season类定义成不可变的,将其Field也定义成final 8 private final String name; 9 private final String desc; 10 public static final Season SPRING 11 =new Season("春天","踏春"); 12 public static final Season SUMMER 13 = new Season("夏天","炎炎"); 14 public static final Season FALL 15 =new Season("秋天","气爽"); 16 public static final Season WINTER 17 =new Season("冬天","赏雪"); 18 public static Season getSeason(int seasomNim){ 19 switch(seasonNum){ 20 case:1 21 return SPRING; 22 break; 23 case:2 24 return SUMMER; 25 break; 26 caes:3 27 return FALL; 28 break; 29 case:4 30 return WINTER; 31 break; 32 default: 33 return null; 34 } 35 } 36 //将构造器定义成private访问权限 37 private Season(String name,String desc){ 38 this.name=name; 39 this.desc=desc; 40 } 41 //只为name和desc提供getter方法 42 public String getName(){ 43 return this.name; 44 } 45 public String getDesc(){ 46 return this.desc; 47 } 48 } 49 50 //测试方法 51 public class SeasonTest{ 52 public SeasonTest(Season s){ 53 System.out.println(s.getName+ 54 s.getDesc()); 55 } 56 public static void main(String[] args){ 57 //直接使用Season的FALL常量代表一个Season对象 58 new SeasonTest(Season.FALL); 59 } 60 } 61 //使用简单的静态常量来表示 62 public static final int SEASON_SPRING=1; 63 public static final int SEASON_SUMMER=2; 64 public static final int SEASON_FALL=3; 65 public static final int SEASON_WINTER=4; 66 67 枚举类实例: 68 public enum SeasonEnum{ 69 //在第一行列出4个枚举实例 70 SPRING,SUMMER,FALL,WINTER; 71 } 72 73 //测试类 74 public class EnumTest{ 75 public void judge(SeasonEnum s){ 76 //switch语句里的表达式可以是枚举类 77 switch(s){ 78 case SPRING: 79 System.out.println("Spring"); 80 break; 81 case SUMMER: 82 System.out.println("Summer"); 83 break; 84 case FALL: 85 System.out.println("Fall"); 86 break; 87 case WINTER: 88 System.out.println("Winter"); 89 break; 90 default: 91 System.out.println("error"); 92 } 93 } 94 public static void main(String[] args){ 95 //所有的枚举类都有values方法,返回该枚举类的所有实例 96 for(SeasonEnum s:SeasonEnum.values()){ 97 System.out.println(s); 98 } 99 //平常使用枚举实例时,总是通过EnumClass.variable的形式访问 100 new EnumTest().judge(SeasonEnum.SPRING); 101 } 102 }