Enum枚举学习- java5之前和之后的写法
Posted amber bar
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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("春天", "春意盎然");只留下有背景颜色的部分。
以上是关于Enum枚举学习- java5之前和之后的写法的主要内容,如果未能解决你的问题,请参考以下文章
Kotlin基础(十四) 枚举类(enum)与java的写法差异