枚举定义
- 枚举类里的值必须是有限个的,确定的。
- 枚举类是一组常量。
- 如果枚举类只有一个对象,则可以作为一个单例的实现方式。
代码示例
JDK1.5之前的写法
//自定义枚举类——JDK1.5之前
public class SeasonEnum {
//1、声明枚举类属性为 private final 防止属性变量被改变
private final int seasonValue;
private final String seasonName;
//2、私有化构造器,防止被创建新的枚举,因为枚举的常量是固定数量的
//并给对象属性赋值
private SeasonEnum(int seasonValue, String seasonName){
this.seasonValue = seasonValue;
this.seasonName = seasonName;
}
//3、声明具体的枚举常量,对外提供使用
public static final SeasonEnum SPRING = new SeasonEnum(1,"SPRING");
public static final SeasonEnum SUMMER = new SeasonEnum(2,"SUMMER");
public static final SeasonEnum AUTUMN = new SeasonEnum(3,"AUTUMN");
public static final SeasonEnum WINTER = new SeasonEnum(4,"WINTER");
//4、提供枚举类对象属性的访问
public int getSeasonValue() {
return seasonValue;
}
public String getSeasonName() {
return seasonName;
}
//5、提供toString()
@Override
public String toString() {
return "SeasonEnum{" +
"seasonValue=" + seasonValue +
", seasonName='" + seasonName + '\'' +
'}';
}
}
JDK1.5及之后的写法
/**
* JDK5创建枚举
* enum关键字创建的枚举类继承于java.lang.Enum,可以通过getParentClass确定
*/
public enum NewSeasonEnum {
//1、枚举对象必须声明在最前面
SPRING(1, "SPRING"),
SUMMER(2, "SUMMER"),
AUTOMN(3, "AUTOMN"),
WINTER(4, "WINTER");
//2、定义枚举属性
private final int index;
private final String name;
//3、私有化构造器,避免被实例化
NewSeasonEnum(int index, String name) {
this.index = index;
this.name = name;
}
//4、提供属性get方法
public int getIndex() {
return index;
}
public String getName() {
return name;
}
//5、根据index获取枚举对象
public static NewSeasonEnum get(int index) {
for (NewSeasonEnum e : NewSeasonEnum.values()) {
if (e.getIndex() == index) {
return e;
}
}
return null;
}
//6、根据index获取枚举对象名
public static String getNameByIndex(int index) {
NewSeasonEnum node = get(index);
return node == null ? null : node.getName();
}
//7、如果需要不只是打印枚举对象名称,则可以重写toString方法
}
public class EnumTest {
@Test
public void test(){
System.out.println(SeasonEnum.AUTUMN);
//SeasonEnum{seasonValue=3, seasonName='AUTUMN'}
System.out.println(NewSeasonEnum.SUMMER);
//SUMMER
}
@Test
public void test2(){
DifferenceSeasonEnum.AUTOMN.show();
DifferenceSeasonEnum.SPRING.show();
//AUTOMN SHOW
//SPRING SHOW
}
}
枚举类实现接口展示不同的表现写法
//让枚举类的对象分别实现接口中的方法,体现出不同的枚举有不同的表现
public enum DifferenceSeasonEnum implements IShow {
//1、枚举对象必须声明在最前面
SPRING(1, "SPRING") {
@Override
public void show() {
System.out.println("SPRING SHOW");
}
},
SUMMER(2, "SUMMER"){
@Override
public void show() {
System.out.println("SUMMER SHOW");
}
},
AUTOMN(3, "AUTOMN"){
@Override
public void show() {
System.out.println("AUTOMN SHOW");
}
},
WINTER(4, "WINTER"){
@Override
public void show() {
System.out.println("WINTER SHOW");
}
};
//2、定义枚举属性
private final int index;
private final String name;
//3、私有化构造器,避免被实例化
DifferenceSeasonEnum(int index, String name) {
this.index = index;
this.name = name;
}
//4、提供属性get方法
public int getIndex() {
return index;
}
public String getName() {
return name;
}
}
public interface IShow {
void show();
}
参考
498-