枚举类的理解
- 类的对象只有有限个,确定的
- 当需要定义一组常量时,强烈建议使用枚举类
- 如果枚举类中只有一个对象,则可以作为单例模式的实现方式
如何定义枚举类
方式一:jdk5.0之前,自定义枚举类(此枚举类继承于Object)
package com.atguigu.java;
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 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、其他诉求1:获取枚举类对象的属性
public String getSeasonName() {
return seasonName;
}
public String getSeasonDesc() {
return seasonDesc;
}
//其他诉求2:提供toSring
@Override
public String toString() {
return "Season{" +
"seasonName='" + seasonName + '\'' +
", seasonDesc='" + seasonDesc + '\'' +
'}';
}
}
方式二:在jdk5.0时,可以用enum关键字定义枚举类(此枚举类继承于java.lang.Enum类)
说明:定义的枚举类继承于class java.lang.Enum,所以toString方法已经重写,输出对象名
package com.atguigu.java;
public class SeasonTest1 {
public static void main(String[] args) {
Season1 spring = Season1.SPRING;
System.out.println(spring);//SPRING
System.out.println(Season1.class.getSuperclass());//查询到父类为class java.lang.Enum
}
}
enum Season1{
//1、提供当前枚举类的对象,多个对象之间用逗号隔开,末尾对象用分号结束
SPRING("春天","春暖花开"),
SUMMER("夏天","夏日炎炎"),
AUTUMN("秋天","秋高气爽"),
WINTER("冬天","冰天雪地");
//2、声明Season对象属性:private final 修饰
private final String seasonName;
private final String seasonDesc;
//3、私有化类的构造器,并给对象属性赋值
private Season1(String seasonName,String seasonDesc){
this.seasonName = seasonName;
this.seasonDesc = seasonDesc;
}
//4、其他诉求1:获取枚举类对象的属性
public String getSeasonName() {
return seasonName;
}
public String getSeasonDesc() {
return seasonDesc;
}
}
Enum类中的常用方法
toString()
返回当前枚举类对象常量的名称
value()
:返回枚举类的对象数组,该方法可以方便的遍历所有枚举值
valueOf(String objName)
:返回枚举类中对象名是objName的对象
如果没有objName的枚举类对象,则抛异常:IllegalArgumentException
System.out.println(spring);//SPRING,调用引用相当于调用该引用的toString()方法
//values()方法的使用
Season1[] values = Season1.values();
for(int i = 0;i < values.length;i++){
System.out.println(values[i]);
}
//valueOf(String objName)方法的使用
Season1 winter = Season1.valueOf("WINTER");
System.out.println(winter);
使用enum关键字定义的枚举类实现接口的情况
- 情况一:实现接口,在enum类中实现抽象方法
- 情况二:让枚举类的对象分别实现接口中的抽象方法
格式:
interface Info{
public void 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("接口实现:冬天");
}
};
网友评论