使用enum关键字定义枚举类
1. 枚举类的说明:
* 1.枚举类的理解:类的对象只有有限个,确定的。我们称此类为枚举类
* 2.当需要定义一组常量时,强烈建议使用枚举类
* 3.如果枚举类中只一个对象,则可以作为单例模式的实现方式。
/**
* @Author lx
* @Description 使用enum关键字定义枚举类
* @Date 9:16 2020/8/11
* @Version
*/
public class EnumTest {
public static void main(String[] args) {
Season1 autumn = Season1.AUTUMN;
System.out.println(autumn);
System.out.println("******");
//values():返回所的枚举类对象构成的数组
Season1[] values = Season1.values();
for (int i = 0;i<values.length;i++){
System.out.println(values[i]);
values[i].show();
}
System.out.println("*******");
//valuesOf(String objName):返回枚举类中对象名是objName的对象。
Season1 winter = Season1.valueOf("WINTER");
System.out.println(winter);
winter.show();
//如果没objName的枚举类对象,则抛异常:IllegalArgumentException
// Season1 winter = Season1.valueOf("WINTER1");
}
}
//定义接口
interface info{
void show();
}
//使用enum定义枚举类
enum Season1 implements info{
//1、先提供对象,多个对象' , '隔开,末尾使用 ' ; '
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("冬天到啦");
}
};
// 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、获取枚举类对象的属性
public String getSEASONNAME() {
return SEASONNAME;
}
public String getSEASONDESC() {
return SEASONDESC;
}
// @Override
// public void show() {
// System.out.println("这是一个季节");
// }
//根据需要决定是否重写toString方法
// @Override
// public String toString() {
// return "Season1{" +
// "SEASONNAME='" + SEASONNAME + '\'' +
// ", SEASONDESC='" + SEASONDESC + '\'' +
// '}';
// }
}
//*************************************************//
////1、自定义枚举类
//class Season1{
// //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;
// }
// //3、提供当前枚举类的多个对象:public static final修饰
// public static final Season1 SPRING = new Season1("春天","春暖花开");
// public static final Season1 SUMMER = new Season1("夏天","夏日炎炎");
// public static final Season1 AUTUMN = new Season1("秋天","秋高气爽");
// public static final Season1 WINTER = new Season1("冬天","白雪皑皑");
//
// //获取枚举类对象的属性
// public String getSEASONNAME() {
// return SEASONNAME;
// }
//
// public String getSEASONDESC() {
// return SEASONDESC;
// }
// //提供toString方法
// @Override
// public String toString() {
// return "Season1{" +
// "SEASONNAME='" + SEASONNAME + '\'' +
// ", SEASONDESC='" + SEASONDESC + '\'' +
// '}';
// }
//}

浙公网安备 33010602011771号