package java0;
/**
*一、枚举类的使用
* 1.枚举类的理解:类的对象只有有限个,确定的,
* 2.需要定义一组常量时,一般使用枚举类
* 3.如果枚举类中只有一个实现对象,则可以作为单例模式的实现方式
*
* 二、如何定义枚举类
* 方式一:JDK5.0之前,自定义枚举类
* 方式二:JDK5.0,可以使用enum关键字定义枚举类
*
* 三、Enum类中常用方法
* 1. values()方法:返回枚举类型的对象数组
* 2. valueOf(String str):返回枚举对象名为str的对象,
* 3. toString():返回当前枚举对象常量的名称
*
* 四、使用enum关键字定义的枚举类实现接口的情况
*
* 情况一:实现接口,在enum类中实现抽象方法
* 情况二:让枚举类中的对象分别实现接口中的抽象方法
*
*
*
* @create 2022-03-23 17:53
*/
public class SeasonTest {
public static void main(String[] args) {
Season test=Season.SPRING;
System.out.println(test);
}
}
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 + '\'' +
'}';
}
}
package java0;
/**
*使用enum关键字定义枚举类
* 说明:定义的枚举类默认继承于java.lang.Enum类
*
*
* @create 2022-03-24 11:12
*/
public class SeasonTest1 {
public static void main(String[] args) {
Season1 summer=Season1.SUMMER;
System.out.println(summer.toString());
Season1[] values=Season1.values();
for (int i = 0; i < values.length; i++) {
System.out.println(values[i]);
values[i].show();
}
Thread.State[] values1=Thread.State.values();
for (int i = 0; i < values1.length; i++) {
System.out.println(values1[i]);
}
Season1 winter=Season1.valueOf("WINTER");
System.out.println(winter);
winter.show();
}
}
interface Info{
void show();
}
enum Season1 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 Season1(String seasonName,String seasonDesc){
this.seasonName=seasonName;
this.seasonDesc=seasonDesc;
}
public String getSeasonName() {
return seasonName;
}
public String getSeasonDesc() {
return seasonDesc;
}
}