其他分享
首页 > 其他分享> > 枚举

枚举

作者:互联网

枚举

枚举的使用

一:如何自定义枚举

package day07;

//测试枚举使用
public class Demo02 {

    public static void main(String[] args) {
        //    方式一:自定义枚举类
        Season spring = Season.SPRING;
        System.out.println(spring.getSeasonName());

        //    方式二:使用enum关键字定义
        Season2 winter = Season2.WINTER;
        System.out.println(winter);
        System.out.println(winter.getSeasonName());
    }
}

//    方式一:自定义枚举类
class Season{
//    1.声明Season对象的属性
    private final String seasonName;
    private final String seasonDesc;

//    2.私有化类的构造器
    private Season(String seasonName,String seasonDesc){
        this.seasonName = seasonName;
        this.seasonDesc = seasonDesc;
    }

//    3.提供当前枚举类的多个对象
    public static final Season SPRING = new Season("春天","春暖花开");
    public static final Season SUMMER = new Season("夏天","夏日炎炎");
    public static final Season AUTUMN = new Season("秋天","秋高气爽");
    public static final Season WINTER = new Season("冬天","冰天雪地");

//    4。获取枚举类对象的属性
    public String getSeasonName() {
        return seasonName;
    }

    public String getSeasonDesc() {
        return seasonDesc;
    }

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


//    方式二:使用enum关键字定义
enum Season2{
    SPRING("春天","春暖花开"),

    SUMMER("夏天","夏日炎炎"),

    AUTUMN("秋天","秋高气爽"),

    WINTER("冬天","冰天雪地");

    //    1.声明Season对象的属性
    private final String seasonName;
    private final String seasonDesc;

    //    2.私有化类的构造器
    private Season2(String seasonName,String seasonDesc){
        this.seasonName = seasonName;
        this.seasonDesc = seasonDesc;
    }

    //    4。获取枚举类对象的属性
    public String getSeasonName() {
        return seasonName;
    }

    public String getSeasonDesc() {
        return seasonDesc;
    }
}

二:Enum类的主要方法

Season2 winter = Season2.WINTER;
System.out.println(winter.toString());

Season2[] value = Season2.values();
for (Season2 season2 : value) {
  System.out.println(season2.getSeasonName());
}

Season2 spring1 = Season2.valueOf("SPRING");
System.out.println(spring1);

三:实现接口的枚举类

标签:String,Season,枚举,seasonName,seasonDesc,public
来源: https://www.cnblogs.com/ZweiShen/p/14308733.html