枚举
作者:互联网
枚举
枚举的使用
一:如何自定义枚举
- 类的对象只有有限个,确定的
- 星期
- 性别
- 支付方式
- 订单状态
- 线程状态:创建、就绪、运行、阻塞、死亡
- 当需要定义一组常量时,强烈建议使用枚举
package day07;
//测试枚举使用
public class Demo02 {
public static void main(String[] args) {
// 方式一:自定义枚举类
Season spring = Season.SPRING;
System.out.println(spring.getSeasonName());
// 方式二:使用enum关键字定义
Season2 winter = Season2.WINTER;
System.out.println(winter);
System.out.println(winter.getSeasonName());
}
}
// 方式一:自定义枚举类
class Season{
// 1.声明Season对象的属性
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("冬天","冰天雪地");
// 4。获取枚举类对象的属性
public String getSeasonName() {
return seasonName;
}
public String getSeasonDesc() {
return seasonDesc;
}
@Override
public String toString() {
return "Season{" +
"seasonName='" + seasonName + '\'' +
", seasonDesc='" + seasonDesc + '\'' +
'}';
}
}
// 方式二:使用enum关键字定义
enum Season2{
SPRING("春天","春暖花开"),
SUMMER("夏天","夏日炎炎"),
AUTUMN("秋天","秋高气爽"),
WINTER("冬天","冰天雪地");
// 1.声明Season对象的属性
private final String seasonName;
private final String seasonDesc;
// 2.私有化类的构造器
private Season2(String seasonName,String seasonDesc){
this.seasonName = seasonName;
this.seasonDesc = seasonDesc;
}
// 4。获取枚举类对象的属性
public String getSeasonName() {
return seasonName;
}
public String getSeasonDesc() {
return seasonDesc;
}
}
二:Enum类的主要方法
- Values():返回枚举类型的对象数组,该方法可以很方便地遍历所有的方法值
- valueOf():可以把一个字符串转换为对应的枚举对象。要求字符串必须是枚举类对象的名字
- toString():返回当前枚举类对象常量的名称
Season2 winter = Season2.WINTER;
System.out.println(winter.toString());
Season2[] value = Season2.values();
for (Season2 season2 : value) {
System.out.println(season2.getSeasonName());
}
Season2 spring1 = Season2.valueOf("SPRING");
System.out.println(spring1);
三:实现接口的枚举类
- 实现接口,在枚举类中实现接口的抽象方法
- 实现接口,让枚举的对象分别在实现接口的抽象方法
标签:String,Season,枚举,seasonName,seasonDesc,public 来源: https://www.cnblogs.com/ZweiShen/p/14308733.html