目录
什么时候使用
1、枚举类的理解:类的对象只有有限个,确定的,我们称此类为枚举类
2、当需要定义一组常量时,强烈建议使用枚举类
3、如果枚举类中只有一个对象,则可以作为单例模式的实现方式
定义一个枚举类
方式1、jdk5.0之前,自定义枚举类
public 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、其他诉求,获取枚举类的属性
@Override
public String toString() {
return "Season{" +
"seasonName='" + seasonName + '\'' +
", SeasonDesc='" + SeasonDesc + '\'' +
'}';
}
}
class test{
public static void main(String[] args) {
Season spring=Season.SPRING;
System.out.println(spring);
}
}
方式2、jdk5.0后可以用enum关键字定义枚举类
public enum MyEnum {
//注意:使用enum关键字定义枚举类,该枚举类默认继承于java.lang.Enum
//1、提供当前枚举类的对象,多个对象之间用,隔开
SPRING("春天","春暖花开"),
SUMMER("夏天","夏日炎炎"),
AUTUMN("秋天","秋高气爽"),
WINTER("冬天","冰天雪地");
private final String seasonName;
private final String seasonDesc;
//2、、私有化构造器
private MyEnum(String seasonName,String seasonDesc )
{
this.seasonName=seasonName;
this.seasonDesc=seasonDesc;
}
public String getSeasonDesc() {
return seasonDesc;
}
public String getSeasonName() {
return seasonName;
}
//默认的toString就是打印当前对象的名字
@Override
public String toString() {
return "MyEnum{" +
"seasonName='" + seasonName + '\'' +
", seasonDesc='" + seasonDesc + '\'' +
'}';
}
public static void main(String[] args) {
System.out.println(MyEnum.SUMMER);
}
}
Enum常用方法
values():返回枚举类型的对象数组。该方法可以很方便地遍历所有的枚举值
valueOf(String str):可以把一个字符串转为对应的枚举类对象。要求字符串必须是枚举类对象的名称
tpString():返回当前枚举类对象常量的名称
Enum类实现接口可以把枚举类的每个对象都实现一遍接口
例如
public enum MyEnum implements into{//该接口中有一个show方法
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("冬天");
}
};
使用:
public static void main(String[] args) {
MyEnum.SUMMER.show();
}