一 概述
JDK5.0之前需要自定义枚举类,而JDK5.0新增的enum关键字用于定于枚举类,若枚举只有一个成员,则可以作为一种单例模式的实现方式
枚举类对象的属性不应允许被改动,所以应该使用private final修饰,应该在构造器为其赋值,若枚举类显式的定义了带参数的个构造器,则在列出枚举类时,也必须对应的传入参数。
二 Enum枚举类
必须在枚举类的第一行声明枚举类对象。
枚举类和普通类的区别:
1.使用enum定义的枚举类默认继承了java.lang.Enum类
2.枚举类的构造器只能使用private访问控制符
3.枚举类的所有实例必须在枚举类中显式列出(,分隔;结尾),列出的实例系统会自动添加 public static final 修饰
JDK5.0中可以在switch表达式中使用Enum定义的枚举类的对象作为表达式,case子句可以直接使用枚举值的名字,无需添加枚举类作为限定。
三 测试
SeasonEnum.java
package com.lxj.Enum; public enum SeasonEnum { SPRING("春天","3-5月"), SUMMER("夏天","3-5月"), ANTUMN("秋天","3-5月"), WINTER("冬天","3-5月"); private final String seasonName; private final String seasonTime; private SeasonEnum(String seasonName,String seasonTime) { this.seasonName = seasonName; this.seasonTime = seasonTime; } public String getSeasonName() { return seasonName; } public String getSeasonTime() { return seasonTime; } }
TestEnum.java
package com.lxj.Enum; public class TestEnum { public static void main(String[] args) { SeasonEnum spring = SeasonEnum.SPRING; System.out.println(spring.getSeasonName()); System.out.println(spring.getSeasonTime()); System.out.print(SeasonEnum.SPRING.name() + " "); System.out.println(SeasonEnum.SPRING.ordinal()); System.out.print(SeasonEnum.SUMMER.name()+ " "); System.out.println(SeasonEnum.SUMMER.ordinal()); System.out.print(SeasonEnum.ANTUMN.name()+ " "); System.out.println(SeasonEnum.ANTUMN.ordinal()); System.out.print(SeasonEnum.WINTER.name()+ " "); System.out.println(SeasonEnum.WINTER.ordinal()); System.out.println("遍历"); SeasonEnum[] seasonEnums = SeasonEnum.values(); for (SeasonEnum seasonEnum : seasonEnums) { System.out.println(seasonEnum); } SeasonEnum enum1 = SeasonEnum.valueOf("SPRING"); System.out.println(enum1); } }
运行结果:
春天
3-5月
SPRING 0
SUMMER 1
ANTUMN 2
WINTER 3
遍历
SPRING
SUMMER
ANTUMN
WINTER
SPRING
测试方法:
SPRING("春天","3-5月"){ public void show() { System.out.println("春天```````````````````````````"); } }, SUMMER("夏天","3-5月"){ public void show() { System.out.println("夏天```````````````````````````"); } }, ANTUMN("秋天","3-5月"){ public void show() { System.out.println("秋天```````````````````````````"); } }, WINTER("冬天","3-5月"){ public void show() { System.out.println("冬天```````````````````````````"); } }; public void show() { }
SeasonEnum.SPRING.show(); SeasonEnum.SUMMER.show(); SeasonEnum.ANTUMN.show(); SeasonEnum.WINTER.show();
运行结果: 春天``````````````````````````` 夏天``````````````````````````` 秋天``````````````````````````` 冬天```````````````````````````