Java篇-枚举的使用

一 : 自定义枚举类

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 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("冬天", "冬天来了");


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

    public void show(){
        System.out.println("hellow");
        
    }
     
}

枚举类调用

public static void main(String[] args) {
        Season spring = Season.SPRING;
        System.out.println(spring);
        spring.show();
        
    }

二 : 使用enum关键字定义枚举类

让枚举类实现接口: 可以让不同的枚举类的对象调用被重写的抽象方法,执行的效果不同,相当于让每个对象重写抽象方法.

//枚举类
enum Season1 implements info{
    
    SPRING("春天", "春天来了"){
        public void show() {
            System.out.println("111");
        }
        
    },
    SUMMER("夏天", "夏天来了"){
        public void show() {
            System.out.println("222");
        }
    },
    AUTUMN ("秋天", "秋天来了"){
        public void show() {
            System.out.println("333");
        }
    },
    WINTER("冬天", "冬天来了"){
        public void show() {
            System.out.println("444");
        }
    };
    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 + "]";
    }

//  public void show(){
//      System.out.println("hellow");
//      
//  }
}

使用values 获取枚举值

Season1 spring = Season1.SPRING;
Season1[] seasons = Season1.values();
        for (int i = 0; i < seasons.length; i++) {
            System.out.println(seasons[i]);
        }

打印结果

Season [seasonName=春天, seasonDesc=春天来了]
Season [seasonName=夏天, seasonDesc=夏天来了]
Season [seasonName=秋天, seasonDesc=秋天来了]
Season [seasonName=冬天, seasonDesc=冬天来了]

使用valueOf(String name)

要求传入的形参name是枚举类对象的名,否则报java.lang.IllegalArgumentException异常

String str = "SPRING";
        Season1 sea = Season1.valueOf(str);
        System.out.println(sea);

打印结果

Season [seasonName=春天, seasonDesc=春天来了]

你可能感兴趣的:(Java篇-枚举的使用)