java之枚举类

java之枚举类

枚举类:

使用自定义创建枚举类

public class TestEnum {
    public static void main(String[] args) {
        Season season1=Season.SPRING1;
        System.out.println(season1);
        System.out.println(season1.getSeasonName());

    }
}
//枚举类
class Season{
    //1.提供类的属性,声明为private final
    private final String seasonName;
    private final String seasonDesc;
    //声明为final的属性,在构造器中初始化
    private Season(String seasonName,String seasonDesc) {
        this.seasonDesc=seasonDesc;
        this.seasonName=seasonName;
    }
    //3.通过公共的方法来调用属性
    public String getSeasonName() {
        return seasonName;
    }
    public String getSeasonDesc() {
        return seasonDesc;
    }

    @Override
    public String toString() {
        return "Season [seasonName=" + seasonName + ", seasonDesc=" + seasonDesc + "]";
    }


    //4.创建枚举类的对象
    public static final Season SPRING1=new Season("seasonName1", "seasonDesc1");
    public static final Season SPRING2=new Season("seasonName2", "seasonDesc2");
    public static final Season SPRING3=new Season("seasonName3", "seasonDesc3");
    public static final Season SPRING4=new Season("seasonName4", "seasonDesc4");


}

使用enum创建枚举类

public class TestEnum {
    public static void main(String[] args) {
        Season season1=Season.SPRING1;
        System.out.println(season1);
        System.out.println(season1.getSeasonName());

        //enum中的方法1
        System.out.println(Season.values());
        for (int i = 0; i < Season.values().length; i++) {
            System.out.println(Season.values()[i]);
        }

        //enum中的方法2  需要传入的是枚举类的名字,否则就会报错
        String str="SPRING1";
        Season sea=Season.valueOf(str);
        System.out.println(sea);

    }
}
//枚举类
enum Season{
    //1.创建枚举类的对象
    SPRING1("seasonName1", "seasonDesc1"),
    SPRING2("seasonName2", "seasonDesc2"),
    SPRING3("seasonName3", "seasonDesc3"),
    SPRING4("seasonName4", "seasonDesc4");

    private final String seasonName;
    private final String seasonDesc;

    private Season(String seasonName,String seasonDesc) {
        this.seasonDesc=seasonDesc;
        this.seasonName=seasonName;
    }

    public String getSeasonName() {
        return seasonName;
    }
    public String getSeasonDesc() {
        return seasonDesc;
    }

    @Override
    public String toString() {
        return "Season [seasonName=" + seasonName + ", seasonDesc=" + seasonDesc + "]";
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值