枚举类
类的对象有限个,确定,叫做枚举类
当需要定义一组常量,强烈建议使用枚举类
当枚举类的对象只有一个时,则可以作为单例模式的方式处理
1.使用enum关键字定义枚举类
public class TestDemo {
public static void main(String[] args) {
Season season = Season.SUMMER;
System.out.println(season);
}
}
public enum Season {
SPRING("春天", "春天到了"),
SUMMER("夏天", "夏天到了"),
AUTUMN("秋天", "秋天到了"),
WINTER("冬天", "冬天到了");
private final String seasonName;
private final String seasonDesc;
private Season(String seasonName, String seasonDesc) {
this.seasonName = seasonName;
this.seasonDesc = seasonDesc;
}
public String getSeasonName() {
return seasonName;
}
public String getSeasonDesc() {
return seasonDesc;
}
}
2.枚举类实现接口
public class TestDemo {
public static void main(String[] args) {
Season season = Season.SUMMER;
System.out.println(season);
season.show();
}
}
public interface Info {
void show();
}
public enum Season implements Info{
SPRING("春天", "春天到了"),
SUMMER("夏天", "夏天到了"),
AUTUMN("秋天", "秋天到了"),
WINTER("冬天", "冬天到了");
private final String seasonName;
private final String seasonDesc;
private Season(String seasonName, String seasonDesc) {
this.seasonName = seasonName;
this.seasonDesc = seasonDesc;
}
public String getSeasonName() {
return seasonName;
}
public String getSeasonDesc() {
return seasonDesc;
}
//所有的方法实现同一个抽象方法
@Override
public void show() {
System.out.println("这是一个季节");
}
}
public class TestDemo {
public static void main(String[] args) {
Season season1 = Season.SUMMER;
Season season2 = Season.SPRING;
System.out.println(season1);
System.out.println(season2);
season1.show();
season2.show();
}
}
public interface Info {
void show();
}
public enum Season 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 Season(String seasonName, String seasonDesc) {
this.seasonName = seasonName;
this.seasonDesc = seasonDesc;
}
public String getSeasonName() {
return seasonName;
}
public String getSeasonDesc() {
return seasonDesc;
}
//所有的方法实现同一个抽象方法
// @Override
// public void show() {
// System.out.println("这是一个季节");
// }
}
3.枚举类中有个API没写的方法values()方法,得到所有的静态不可变的枚举对象