java enum

2021-04-20 12:27

阅读:406

标签:private   fine   vat   int   final   loading   test   class   ring   

Self-defined Enum

//Season.java
public class Season {
    // step1: fields which are private final
    private final String seasonName;
    private final String seasonDesc;

    // step2 : private Constructor
    private Season(String seasonName, String seasonDesc){
        this.seasonName = seasonName;
        this.seasonDesc = seasonDesc;
    }

    // step3 : create some enum object
    public static final Season SPRING = new Season("Spring", "Go hiking");
    public static final Season SUMMER = new Season("Summer", "Go swimming");
    public static final Season AUTUMN = new Season("Autumn", "Go picking");
    public static final Season WINTER = new Season("Winter", "Go skiing");

    // step 4: you can have the getter

    public String getSeasonName() {
        return seasonName;
    }

    public String getSeasonDesc() {
        return seasonDesc;
    }

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

}
// test
 @org.junit.Test
    public void testSeasonEnum(){
        Season spring = Season.SPRING;
        System.out.println(spring.toString()); // Season{seasonName=‘Spring‘, seasonDesc=‘Go hiking‘}
    }

And when you use "enum"


public enum  SeasonTest1 {
    SPRING("Spring", "Go hiking"),
    SUMMER("Summer", "Go swimming"),
    AUTUMN("Autumn", "Go picking"),
    WINTER("Winter","Go skiing");

    private final String seasonName;
    private final String seasonDesc;

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

    public String getSeasonName() {
        return seasonName;
    }

    public String getSeasonDesc() {
        return seasonDesc;
    }
    
}


The Enum Class

技术图片

you have to know, when you use "enum", you actually extend Enum class

// values() 
SeasonTest1[] values = SeasonTest1.values();
        for (SeasonTest1 season : values){
            System.out.println(season); // SPRIN SUMMER AUTUMN WINTER
        }

技术图片

java enum

标签:private   fine   vat   int   final   loading   test   class   ring   

原文地址:https://www.cnblogs.com/nedrain/p/13285699.html


评论


亲,登录后才可以留言!