一、枚举类的使用
1、枚举类的理解:类的对象只有有限个,确定的,我们称此类为枚举类。
2、当需要定义一组常量时,强烈建议用枚举类。
3、如果枚举类中只有一个对象,则可以作为单列模式的实现方式。
二、枚举类的创建
1、自定义枚举类
public class Main
{
public static void main(String[] args){
Season season = Season.SPRING;
System.out.println(season);
}
}
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 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 + '\'' +
'}';
}
}
2、enum关键字定义(默认继承于java.lang.Enum)
public class Main
{
public static void main(String[] args){
Season season = Season.SPRING;
System.out.println(Season.class.getSuperclass());
}
}
enum Season{
//提供当前枚举类的多个对象,用逗号隔开,最后一个写分号
SPRING("春天","春暖花开"),
SUMMER("夏天","夏日炎炎"),
AUTUMN("秋天","秋高气爽"),
WINTER("冬天","冰天雪地");
private final String seasonName;
private final String seasonDesc;
private Season(String seasonName,String seasonDesc) {
this.seasonName = seasonName;
this.seasonDesc = seasonDesc;
}
public String getSeasonName() {
return seasonName;
}
public String getSeasonDesc() {
return seasonDesc;
}
}
三、Enum类常用方法
values():返回枚举类的对象数组,方便遍历所有枚举值。
valueOf(String s):找到名为s的对象,如果没有名为s的对象,则抛异常
Season[] values = Season.values();
Season winter = Season.valueOf("WINTER");
四、让枚举类对象分别实现接口
public class Main
{
public static void main(String[] args){
Season[] values = Season.values();
for (int i = 0; i < values.length; i++) {
values[i].show();
}
}
}
//接口
interface info{
void show();
}
//实现接口
enum Season implements info{
//提供当前枚举类的多个对象
SPRING("春天","春暖花开"){
@Override
public void show() {
System.out.println("春天在哪里呀,春天在哪里");
}
},
SUMMER("夏天","夏日炎炎"){
@Override
public void show() {
System.out.println("夏天夏天悄悄过去,留下小秘密");
}
},
AUTUMN("秋天","秋高气爽"){
@Override
public void show() {
System.out.println("秋天不回来");
}
},
WINTER("冬天","冰天雪地"){
@Override
public void show() {
System.out.println("雪花飘飘,北风啸啸");
}
};
private final String seasonName;
private final String seasonDesc;
private Season(String seasonName,String seasonDesc) {
this.seasonName = seasonName;
this.seasonDesc = seasonDesc;
}
}