枚举:
1 public enum YearEnum { 2 SPRING,SUMMER,AUTUMN,WINTER; 3 } 4 5
YearEnum 是一个枚举类型,SPRING,SUMMER,AUTUMN,WINTER 是它的内部类。
YearEnum yearEnum=YearEnum.SPRING; 相当于用YearEnum的静态工厂法返回一个SPRING的实例。
enum型类枚举是抽象类,因此可以在其中声明abstract方法,并让每个子类:SPRING,SUMMER,AUTUMN,WINTER 实现其方法。
1 public enum Menu implements Food { 2 3 SUNDAY("星期天") { 4 @Override 5 public String getFood() { 6 // TODO Auto-generated method stub 7 return "饺子"; 8 } 9 }, 10 MONDAY("星期一") { 11 @Override 12 public String getFood() { 13 // TODO Auto-generated method stub 14 return "蛋黄酱"; 15 } 16 }, 17 TUESDAY("星期二") { 18 @Override 19 public String getFood() { 20 // TODO Auto-generated method stub 21 return "肉"; 22 } 23 }, 24 WEDNESDAY("星期三 ") { 25 @Override 26 public String getFood() { 27 // TODO Auto-generated method stub 28 return "红豆面包"; 29 } 30 }, 31 THURSDAY("星期四") { 32 @Override 33 public String getFood() { 34 // TODO Auto-generated method stub 35 return "香蕉"; 36 } 37 }, 38 FRIDAY("星期五") { 39 @Override 40 public String getFood() { 41 // TODO Auto-generated method stub 42 return "螺丝起子"; 43 } 44 }, 45 SATURDAY("星期六") { 46 @Override 47 public String getFood() { 48 // TODO Auto-generated method stub 49 return "小松"; 50 } 51 }; 52 53 // public abstract String getFood(); 54 55 private String chinaName; 56 57 private Menu(String chinaName) { 58 this.chinaName = chinaName; 59 } 60 61 public String getChinaName() { 62 return chinaName; 63 } 64 65 }
接口:
1 public interface Food { 2 public String getFood(); 3 }
测试类:
1 public class Test { 2 3 public static void main(String[] args) { 4 for (Menu menu : Menu.values()) { 5 System.out.print("今天是:"+menu.getChinaName()); 6 if (menu.ordinal()==0|menu.ordinal()==6) { 7 System.out.print(" 今天是休息日"); 8 }else { 9 System.out.print(" 今天是工作日"); 10 } 11 System.out.println(" 食谱:"+menu.getFood()); 12 } 13 } 14 15 }