枚举类的常用方法
最长使用的三个方法
values()-----------获取枚举里边的所有对象
valueOf()-----------把一个字符串类型的值转换成枚举对象【前提字符串是枚举对象里的名字,否则报错】
toString()----------打印时使用,返回枚举名称【可以重写枚举类的方法,得到自己想要的打印】
使用
枚举类
package com.atguigu.entity;
public enum Season {
SPRING("春天","春暖花开"),
SUMMER("夏天","烈日炎炎"),
AUTUMN("秋天","秋高气爽"),
WINTER("冬天","冰天雪地");
private Season(String seasonName,String seasonDesc){
this.seasonName = seasonName;
this.seasonDesc = seasonDesc;
}
private final String seasonName;
private final String seasonDesc;
//使用final关键字,对象是常量,其属性不能再被改变
public final String getSeasonName() {
return seasonName;
}
public String getSeasonDesc() {
return seasonDesc;
}
}
测试类
package com.atguigu.entity;
public class TestSeason {
public static void main(String[] args) {
没有重写枚举类里的.toString(),直接打印的是枚举对象的名称,不是地址值,因为枚举类的父类不是Object
System.out.println(Season.AUTUMN);
System.out.println(Season.AUTUMN.getSeasonName());
System.out.println(Season.AUTUMN.getSeasonDesc());
//获取AUTUMN的对象代表的类
System.out.println(Season.AUTUMN.getClass());
//获取AUTUMN的对象代表的枚举类父类【父类是Enum类,而非Object】
System.out.println(Season.AUTUMN.getClass().getSuperclass());
//获取枚举类里所有的对象
Season[] values = Season.values();
for (Season season : values) {
System.out.println(season);
}
//将字符串AUTUMN转化为枚举类里的对象
Season autumn = Season.valueOf("AUTUMN");
System.out.println(autumn);
//报错
Season autumn2 = Season.valueOf("autumn");
System.out.println(autumn);
}
}