1. 程式人生 > >Enum列舉學習- java5之前和之後的寫法

Enum列舉學習- java5之前和之後的寫法

enum列舉

JDK1.5以前列舉的寫法

/**
 * java5.0以前,定義列舉類。類中的物件是有限的
 * @author amber
 *
 */
public class Season {
    private final String seasonName;
    private final String seasonDescription;
    
    private Season(String seasonName, String seasonDescription) {
        this.seasonName = seasonName;
        
this.seasonDescription = seasonDescription; } public String getSeasonName() { return seasonName; } public String getSeasonDescription() { return seasonDescription; } //定義列舉物件 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 + ", seasonDescription=" + seasonDescription + "]"; } }

java5以後列舉的寫法

/**
 * java5.0以後,定義列舉類。類中的物件是有限的
 * @author amber
 *
 */
public enum Season1 {
    //定義列舉物件.需要把物件放在第一行
    SPRING ("春天", "春意盎然"){
        @Override
        public void show() {
            System.out.println("This is Spring!");
        }
    },
    SUMMER ("夏天", "夏日炎炎"),
    AUTUMN ("秋天", "秋風習習"),
    WINTER ("冬天", "白雪皚皚");
    
    private final String seasonName;
    private final String seasonDescription;
    
    private Season1(String seasonName, String seasonDescription) {
        this.seasonName = seasonName;
        this.seasonDescription = seasonDescription;
    }
    public void show() {
        System.out.println("This is Season!");
    }
    public String getSeasonName() {
        return seasonName;
    }

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

 

區別:

使用enum的時候

類物件必須放在第一行,分號改成逗號。最後一個物件用分號。並且把原來的

public static final Season SPRING = new Season("春天", "春意盎然");只留下有背景顏色的部分。