public class Enumeration01 { public static void main(String[] args) { Season.SPRING.getName(); } } class Season { private String name; private String desc; 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("冬天", "寒冷"); private Season(String name, String desc) { this.name = name; this.desc = desc; } public String getName() { return this.name; } public String getDesc() { return this.desc; } }
enum Season2 { /* 1. 使用关键字enum代替class 2. public static final Season SPRING = new Season("春天", "温暖");直接使用SPRING("春天", "温暖") 3. 如果有多个对象,之间用,间隔即可 4. 如果使用enum来实现枚举,要求将定义常量对象卸载前面 */ SPRING("春天", "温暖"),SUMMER("夏天", "炎热"),AUTUMN("秋天", "凉爽"),WINTER("冬天", "寒冷"); private String name; private String desc; // 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("冬天", "寒冷"); private Season2(String name, String desc) { this.name = name; this.desc = desc; } public String getName() { return this.name; } public String getDesc() { return this.desc; } }
注意事项
D:\own_code\vst\design-diagrams\target\classes\com\original\base\enumeration>javap Season2.class Compiled from "Enumeration01.java" final class com.original.base.enumeration.Season2 extends java.lang.Enum<com.original.base.enumeration.Season2> { public static final com.original.base.enumeration.Season2 SPRING; public static final com.original.base.enumeration.Season2 SUMMER; public static final com.original.base.enumeration.Season2 AUTUMN; public static final com.original.base.enumeration.Season2 WINTER; static {}; public java.lang.String getName(); public java.lang.String getDesc(); public static com.original.base.enumeration.Season2[] values(); public static com.original.base.enumeration.Season2 valueOf(java.lang.String); } D:\own_code\vst\design-diagrams\target\classes\com\original\base\enumeration>
// 下面代码会输出什么 enum Gender2{ BOY,GIRL; } Gender2 boy = Gender2.BOY; Gender2 boy2 = Gender2.BOY; System.out.println(boy); // 本质是调用Gender2的toString BOY System.out.println(boy == boy2) // True
Enum常用方法
public static void main(String[] args) { Season2 autumn = Season2.AUTUMN; // 输出枚举对象的名称 System.out.println(autumn.name());// AUTUMN // 该模具对象的次序/编号,从0开始编号的 System.out.println(autumn.ordinal()); // 2 // 从反编译可以看出 values方法,返回Season2[],含有定义的所有枚举对象 Season2[] seasons = Season2.values(); for (Season2 season2 : seasons) { System.out.println(season2.getName()); } // valueOf:将字符串转换成枚举对象,要求字符串必须为已有的常量名否则报异常 Season2 autumn2 = Season2.valueOf("AUTUMN"); // comparaTo 比较枚举常量的ordinal编号 AUTUMN编号减去WINTER编号 System.out.println(Season2.AUTUMN.compareTo(Season2.SUMMER)); // -1 }
@Interface不是interface,是注解类在jdk1.5之后加入
三个基本的Annotation:
元注解的基本介绍,JDK的元Annotation用于修饰其他Annotation,元注解本身作用不大