一,自定义枚举
枚举类中声明的每一个枚举值代表枚举类的一个实例对象
与Java中的普通类一样,在声明枚举类时,也可以声明属性、方法和构造函数
但是枚举类的构造函数必须为私有的,我们一起来练习一下:
package cn.cxy.exec;
/*本类用于自定义枚举类*/
public class SeasonTest {
public static void main(String[] args) {
System.out.println(Season.SPRING.getSEASON_NAME());//春季
System.out.println(Season.SUMMER.getSEASON_DESC());//夏日炎炎
System.out.println(Season.AUTUMN);
//Season{SEASON_NAME='秋季', SEASON_DESC='秋高气爽'}
}
}
//1.自定义枚举类
class Season{
//2.定义本类的私有属性,为了防止值被修改,需要设置为final
private final String SEASON_NAME;//季节名
private final String SEASON_DESC;//季节描述
//3.私有化本类的构造方法--防止外界随意创建本类对象
private Season(String seasonName,String seasonDesc){
this.SEASON_NAME = seasonName;//在构造中给本类的属性赋值
this.SEASON_DESC = seasonDesc;
}
//4.提供当前枚举类的多个对象
public final static Season SPRING = new Season("春季","春暖花开");
public final static Season SUMMER = new Season("夏季","夏日炎炎");
public final static Season AUTUMN = new Season("秋季","秋高气爽");
public final static Season WINTER = new Season("冬季","冬雪凛凛");
//5.生成对应的get的方法,获取本类的两个属性值
public String getSEASON_NAME() {
return SEASON_NAME;
}
public String getSEASON_DESC() {
return SEASON_DESC;
}
//6.生成toString方法方便查看
@Override
public String toString() {
return "Season{" +
"SEASON_NAME='" + SEASON_NAME + '\'' +
", SEASON_DESC='" + SEASON_DESC + '\'' + '}';
}
}
二,使用关键字enum定义枚举类
package cn.cxy.exec;
/*本类用于使用enum关键字定义枚举类*/
public class ColorTest {
public static void main(String[] args) {
//6.进行测试
System.out.println(Color.RED);//RED
System.out.println(Color.ORANGE.getCOLOR_NAME());//橙色
System.out.println(Color.ORANGE.getCOLOR_NUMBER());//2
}
}
//1.使用enum关键字定义枚举类
enum Color {
//2.写出本类对应的多个枚举对象
/*1.public static final可以省略不写
* 2.枚举对象不能像自定义枚举类对象时new,要按照下面的语法:
* 枚举名1(值1,值2),枚举名2(值1,值2),枚举名3(值1,值2);
* 3.不需要生成toString,因为使用enum关键字定义的枚举类继承了java.lang.Enum
* 在Enum中重写了继承自Object的toString(),直接打印的就是枚举名*/
RED("红色",1),
ORANGE("橙色",2),
YELLOW("黄色",3),
GREEN("绿色",4),
CYAN("青色",5),
BLUE("蓝色",6),
PURPLE("紫色",7);
//3.定义枚举类的多个私有属性
private final String COLOR_NAME;
private final int COLOR_NUMBER;
//4.定义本类的构造方法
private Color(String colorName, int colorNumber) {
this.COLOR_NAME = colorName;
this.COLOR_NUMBER = colorNumber;
}
//5.生成属性对应的两个get()
public String getCOLOR_NAME() {
return COLOR_NAME;
}
public int getCOLOR_NUMBER() {
return COLOR_NUMBER;
}
}