枚举类
一、枚举类的使用
- 枚举类的理解:类的对象是有限个,确定的。我们称此类为枚举类
- 当需要定义一组常量时(订单状态,一年的季节,支付方式等),强烈建议使用枚举类
- 如果枚举类中只有一个对象,则作为单例模式的实现方式(单例的写法之一)
二、如何定义枚举类
- 自定义枚举类
/**
* @Author Helius
* @Create 2019-05-19-21:48
*/
public class SeasonTest {
public static void main(String[] args) {
Season spring = Season.SPRING;
System.out.println(spring);
}
}
/**
* 自定义枚举类
*/
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的
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;
}
//5.提供toString()
@Override
public String toString() {
return "Season{" +
"seasonName='" + seasonName + '\'' +
", seasonDesc='" + seasonDesc + '\'' +
'}';
}
}
打印结果:
Season
- 使用enum关键字
public class SeasonTest1 {
public static void main(String[] args) {
Season1 summer = Season1.SUMMER;
System.out.println(summer);
}
}
// 使用enum关键字
enum Season1 {
// 1.提供当前枚举类的对象,多个对象之间用","隔开,末尾对象“;”结束
// 最主要的区别在这里
SPRING("春天", "春暖花开"),
SUMMER("夏天", "夏日炎炎"),
AUTUMN("秋天", "秋高气爽"),
WINTER("冬天", "冰天雪地");
// 1.声明Season1对象的属性,private,final修饰
private final String Season1Name;
private final String Season1Desc;
// 2.私有化类的构造器
private Season1(String Season1Name, String Season1Desc) {
this.Season1Name = Season1Name;
this.Season1Desc = Season1Desc;
}
// 4.获取枚举类对象的属性
public String getSeason1Name() {
return Season1Name;
}
public String getSeason1Desc() {
return Season1Desc;
}
}
打印结果:
SUMMER // 并未打印对象的地址值,而是打印出summer,说明toString方法被重写过,可以不再重写
class java.lang.Enum // 枚举类的父类
三、Enum的常用方法
public class SeasonTest1 {
public static void main(String[] args) {
Season1 summer = Season1.SUMMER;
// toString方法
System.out.println(summer.toString());
System.out.println("***********");
// System.out.println(Season1.class.getSuperclass());
// values()方法
Season1[] values = Season1.values();
for (Season1 value : values) {
System.out.println(value);
}
// valueOf(String objNme):返回枚举类中对象名为objName的对象
// 如果没有objName的枚举类对象,则抛异常:IllegalArgumentException
Season1 winter = Season1.valueOf("WINTER");
System.out.println(winter);
}
}
四、枚举类实现接口
实现接口的抽象方法即可,可以为每个枚举类对象分别提供实现
SPRING("春天", "春暖花开"){
@Override
public void show() {
System.out.println(“春天在哪里);
}
},
你所看得到的天才不过是在你看不到的时候还在努力罢了!