枚举enum 的全称为 enumeration, 是 JDK 1.5 中引入的新特性,存放在 java.lang 包中。
枚举定义类:
package enums;
public enum SexEnum {
Man("Tom"){
public String sayInfo(){
return getName();
}
},
Woman("Lily"){
public String sayInfo(){
return getName();
}
};
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
private SexEnum(String name){
this.name = name;
}
public abstract String sayInfo();
}
枚举测试类:
package enums;
/**
* 枚举测试类
* @author LD
*
*/
public class EnumTest {
public static void main(String[] args) throws Exception {
testEnum(SexEnum.Man);
testEnum(SexEnum.Woman);
}
private static void testEnum(SexEnum sex) {
switch (sex) {
case Man:
System.out.println("This is a man,"+sex.Man.sayInfo());
break;
case Woman:
System.out.println("This is a woman,"+sex.Woman.sayInfo());
break;
default:
System.err.println("I don't known your sex");
break;
}
}
}
结果:
This is a man,Tom
This is a woman,Lily