码迷,mamicode.com
首页 > 编程语言 > 详细

Enum枚举学习- java5之前和之后的写法

时间:2018-11-01 17:48:53      阅读:124      评论:0      收藏:0      [点我收藏+]

标签:ide   otto   pre   5.0   部分   背景   summer   err   private   

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("春天", "春意盎然");只留下有背景颜色的部分。

 

 

Enum枚举学习- java5之前和之后的写法

标签:ide   otto   pre   5.0   部分   背景   summer   err   private   

原文地址:https://www.cnblogs.com/amberbar/p/9882908.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!