枚举类
程序员文章站
2022-07-15 10:40:17
...
1、枚举类:就是对象的实例个数是确定的(例如:单例模式),也就说我们在创建枚举类的时候,会对构造器进行设置。
2、自定义创建枚举类:
package com.atguigu.java1;
public class TestSeason {
public static void main(String[] args) {
Season spring = Season.SPRING;
System.out.println(spring);
spring.show();
System.out.println(spring.getSeasonName());
}
}
//枚举类
class Season{
//1.提供类的属性,声明为private final
private final String seasonName;
private final String seasonDesc;
//2.声明为final的属性,在构造器中初始化。
private Season(String seasonName,String seasonDesc){
this.seasonName = seasonName;
this.seasonDesc = seasonDesc;
}
//3.通过公共的方法来调用属性
public String getSeasonName() {
return seasonName;
}
public String getSeasonDesc() {
return seasonDesc;
}
//4.创建枚举类的对象:将类的对象声明public static final
public static final Season SPRING = new Season("spring", "春暖花开");
public static final Season SUMMER = new Season("summer", "夏日炎炎");
public static final Season AUTUMN = new Season("autumn", "秋高气爽");
public static final Season WINTER = new Season("winter", "白雪皑皑");
@Override
public String toString() {
return "Season [seasonName=" + seasonName + ", seasonDesc="
+ seasonDesc + "]";
}
public void show(){
System.out.println("这是一个季节");
}
}
3、使用enum关键字创建枚举类(必须将生命的对象放在最前面,同时去掉重复的部分)并且之间用逗号隔开。其他与我们之前创建时一致的。//枚举类
enum Season1{
SPRING("spring", "春暖花开"),
SUMMER("summer", "夏日炎炎"),
AUTUMN("autumn", "秋高气爽"),
WINTER("winter", "白雪皑皑");
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;
}
@Override
public String toString() {
return "Season [seasonName=" + seasonName + ", seasonDesc="
+ seasonDesc + "]";
}
}
4、枚举类中主要使用的两个方法: //1.values():已数组的方式,获取所有的枚举成员
Season1[] seasons = Season1.values();
for(int i = 0;i < seasons.length;i++){
System.out.println(seasons[i]);
}
//2.valueOf(String name):要求传入的形参name是枚举类对象的名字,获取枚举对象。
//否则,报java.lang.IllegalArgumentException异常
String str = "WINTER";
Season1 sea = Season1.valueOf(str);
5、实现接口:特殊之处在于,当每一对象需要单独实现show方法时,可以通过{}的形式,来完成需求。
interface Info{
void show();
}
//枚举类
enum Season1 implements Info{
SPRING("spring", "春暖花开"){
public void show(){
System.out.println("春天在哪里?");
}
},
SUMMER("summer", "夏日炎炎"){
public void show(){
System.out.println("生如夏花");
}
},
AUTUMN("autumn", "秋高气爽"){
public void show(){
System.out.println("秋天是用来分手的季节");
}
},
WINTER("winter", "白雪皑皑"){
public void show(){
System.out.println("冬天里的一把火");
}
};
上一篇: 数组中只出现一次的两个数字
下一篇: 词法作用域 & 欺骗语法