【Java】枚举类
1.枚举类
- 类的对象只有有限个,对象是确定的。
- 当需要定义一组常量时,强烈建议使用枚举类。
- 如果枚举类中只有一个对象,则可以作为单例模式的实现方式。
2.定义枚举类
- JDK 5.0之前:自定义枚举类
- JDK 5.0之后:使用enum关键字定义
(1)自定义枚举类
public class Season {
//1.对象属性private final修饰
private final String seasonName;
private final String seasonDesc;
//2.私有构造器
private Season(String seasonName,String seasonDesc){
this.seasonName = seasonName;
this.seasonDesc = seasonDesc;
}
//3.当前枚举类的多个对象,public static final修饰
public static final Season SPRING = new Season("春天","春暖花开");
public static final Season SUMMER = new Season("夏天","夏日炎炎");
public static final Season AUTUMN = new Season("秋天","秋高气爽");
public static final Season WINTER = new Season("冬天","冰天雪地");
public String getSeasonName() {
return seasonName;
}
public String getSeasonDesc() {
return seasonDesc;
}
@Override
public String toString() {
return "Season{" +
"seasonName='" + seasonName + '\'' +
", seasonDesc='" + seasonDesc + '\'' +
'}';
}
}
调用时直接通过类名.对象
System.out.println(Season.SPRING);
(2)使用enum
- 所有对象要写在开头,否则会报错。
- 对象之间用逗号隔开,结尾用分号。
- 定义的枚举类默认继承于java.lang.Enum类
enum Season {
SPRING("春天", "春暖花开"),
SUMMER("夏天", "夏日炎炎"),
AUTUMN("秋天", "秋高气爽"),
WINTER("冬天", "冰天雪地");
private final String seasonName;
private final String seasonDesc;
private Season(String seasonName, String seasonDesc) {
this.seasonName = seasonName;
this.seasonDesc = seasonDesc;
}
public String getSeasonName() {
return seasonName;
}
public String getSeasonDesc() {
return seasonDesc;
}
@Override
public String toString() {
return "Season{" +
"seasonName='" + seasonName + '\'' +
", seasonDesc='" + seasonDesc + '\'' +
'}';
}
}
常用方法
System.out.println(Season2.SUMMER); //调用方式
System.out.println(Season2.valueOf("WINTER")); //返回指定对象名的对象
Season2[] seasons = Season2.values(); //返回所有的枚举类对象构成的数组
for (int i = 0; i < seasons.length; i++) {
System.out.println(seasons[i]);
}
Thread.State[] states = Thread.State.values(); //返回所有线程状态
for (int i = 0; i < states.length; i++) {
System.out.println(states[i]);
}