枚举类
enum常用方法
- toString:Enum已经重写,返回当前对象名,子类可以重写该方法,用于返回对象的属性信息。
- name:返回当前对象名(常量名),子类中不能重写。
- ordinal:返回当前对象的下标。
- values:返回当前枚举类中的所有常量。
- valueOf:将字符串转换为枚举对象,要求字符串必须为已有的常量名,否则报错
- compaperTo:比较两个枚举常量,比较的是下标。返回值为下标差。
sout(Season2.AUTUMN.compaperTo(Season2.SUMMER));
使用细节
- enum已经默认继承Enum类,不能再继承其他类
- 可以实现接口
为public static final类型的
class Season {
private final String seasonName;
private final String SeasonDesc;
private Season(String seasonName, String seasonDesc) {
this.seasonName = seasonName;
this.SeasonDesc = seasonDesc;
}
// 提供当前枚举类的多个对象。必须声明为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 + '\'' +
'}';
}
}
public class SeasonTest {
public static void main(String[] args) {
Season autumn = Season.AUTUMN;
System.out.println(autumn);
}
}