看源码和注解
<span style="font-size:14px;">package com.demo.controller;
import java.io.Console;
public class EnumTest {
//枚举都是常量,最好变量名全是大写,用于区分
public enum Seasons{
spring,
summer,
fall,
winter
};
//用法1 定义常量
public enum Days{
Sunday,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday
}
//用法2 向枚举添加新方法
//必须在enum实例序列的最后添加一个分号。而且 Java 要求必须先定义 Enum 实例。
public enum Color{
//利用构造参数传递参数
RED("红色",1), GREEN("绿色",2), YELLOW("黄色",3);
//成员变量
private String name;
private Integer index;
//constructor,只能为private
private Color(String name, Integer index){
this.name = name;
this.index = index;
}
public static String getName(int index){
for(Color col : Color.values()){
if(col.getIndex() == index){
System.out.println(col.name);
return col.name;
}
}
return null;
}
//用法3 重写toString方法
@Override
public String toString(){
System.out.println(this.index+"_"+this.name);
return this.index+"_"+this.name;
}
//Getter And Setter
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getIndex() {
return index;
}
public void setIndex(Integer index) {
this.index = index;
}
}
//遍历Seasons
public static void iterateSeasons(){
System.out.println(Seasons.values());
for(Seasons s:Seasons.values()){
System.out.println(s);
System.out.println(s.getClass().getName());
}
}
//用法4 调用swtich,判断周几
public static void iterateDays(Days day){
//Days day = (Days)Enum.parse(typeof(Days), day);
switch(day){
case Sunday : System.out.println("星期天休息");break;
case Friday : System.out.println("星期五约会");break;
default:System.out.println("其余天都上班");break;
}
}
//用法5 实现接口
//用法6
public static void main(String[] args) {
//iterateSeasons();
//iterateDays(Days.Friday);
//Color.getName(1);
Color.YELLOW.toString();
}
}
</span>
参考链接: http://www.cnblogs.com/happyPawpaw/archive/2013/04/09/3009553.html