创建Java不可变型的枚举类型,其实例如下:
1 // 创建不可变型的枚举类 2 enum Gender { 3 // 此处的枚举值必须调用对应的构造器来创建 4 MALE("男"), FEMALE("女"); 5 6 // 或者,使用下面两个语句代替上面语句 7 // public static final Gender MALE = new Gender("男"); 8 // public static final Gender FEMALE = new Gender("女"); 9 10 private final String name;11 12 // 枚举类的构造器只能使用private修饰,以使其不可变13 private Gender(String name) {14 this.name = name;15 }16 17 public String getName() {18 return this.name;19 }20 }21 22 23 public class GenderImmutableTest {24 public static void main(String[] args) {25 Gender g = Gender.MALE;26 System.out.println(g + ":" + g.getName()); 27 }28 }