来自:《代码大全》
在Java没有C++中的枚举类型,有时候会很不方便,下面的方法可以实现
-
class Country {
-
private Country() {}
-
public static final Country China = new Country();
-
public static final Country England = new Country();
-
public static final Country France = new Country();
-
public static final Country Germany = new Country();
-
public static final Country India = new Country();
-
}
这种特殊的创建枚举的方法是类型安全的(type safe),因为编译器会检查非法的赋值
-
Output output = Country.England; //编译不通过