1、枚举概述
- 枚举类的理解:类的对象只有有限个,确定的。我们称此为枚举类。
- 当需要定义一组常量时,强烈建议使用枚举类。
- 如果枚举类中只有一个对象,则可以作为单例模式的实现方式。
2、如何定义枚举类
1. JDK5.0之前,自定义枚举类
2. JDK5.0之后,可以使用enum关键字定义枚举类
2.1、自定义枚举类
public class Main {
public static void main(String[] args) {
Season spring = Season.SPRING;
Season summer = Season.SUMMER;
Season autumn = Season.AUTUMN;
Season winter = Season.WINTER;
System.out.println(spring);
System.out.println(summer);
System.out.println(autumn);
System.out.println(winter);
}
}
//自定义枚举类
class Season {
//1、声明Season对象的属性: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 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;
}
//提供toString()方法
@Override
public String toString() {
return "Season{" +
"seasonName='" + seasonName + '\'' +
", seasonDesc='" + seasonDesc + '\'' +
'}';
}
}
2.2、使用enum定义枚举类
public class Main {
public static void main(String[] args) {
Season spring = Season.SPRING;
Season summer = Season.SUMMER;
Season autumn = Season.AUTUMN;
Season winter = Season.WINTER;
System.out.println(spring);
System.out.println(summer);
System.out.println(autumn);
System.out.println(winter);
}
}
//使用enum定义枚举类
enum Season {
//1、提供当前枚举类的对象,多个对象之间用逗号隔开,末尾用分号。
SPRING("春天","春暖花开"),
SUMMER("夏天","夏日炎炎"),
AUTUMN("秋天","秋风送爽"),
WINTER("冬天","冬虫夏草");
//1、声明Season对象的属性:private final修饰
private final String seasonName;
private final String seasonDesc;
//2、私有化构造器,并给对象属性赋值
private Season(String seasonName, String seasonDesc) {
this.seasonName = seasonName;
this.seasonDesc = seasonDesc;
}
//获取枚举类属性
public String getSeasonName() {
return seasonName;
}
public String getSeasonDesc() {
return seasonDesc;
}
}
定义的枚举类默认继承于java.lang.Enum类
3、Enum类中的常用方法
Values():返回枚举类型的对象数组。该方法可以很方便地遍历所有的枚举值
public class Main {
public static void main(String[] args) {
Season[] values = Season.values();
for (Season s:values) {
System.out.println(s);
}
}
}
valueOf():可以把一个字符串转为对应地枚举类对象。要求字符串必须是枚举类对象的"名字"。如不是,会有运行时异常。
public class Main {
public static void main(String[] args) {
//valueOf(String objName):返回枚举类中对象名时objName的对象
Season winter = Season.valueOf("WINTER");
System.out.println(winter);
}
}
如果没有objName的枚举类对象,则抛异常IllegalArgumentException
如果对大家有用的话,可以点赞关注和收藏哦,谢谢各位!