假设你使用常量字符串(或int值 – 对于它们同样如此):
// Constants for player types
public static final String ARCHER = "Archer";
public static final String WARRIOR = "Warrior";
// Constants for genders
public static final String MALE = "Male";
public static final String FEMALE = "Female";
那么你最终不知道你的数据的类型 – 导致潜在的错误代码:
String playerType = Constants.MALE;
如果你使用枚举,那么最终会是:
// Compile-time error - incompatible types!
PlayerType playerType = Gender.MALE;
同样,枚举给出一组有限的值:
String playerType = "Fred"; // Hang on, that's not one we know about...
vs
PlayerType playerType = "Fred"; // Nope, that doesn't work. Bang!
此外,Java中的枚举可以有更多的相关信息,也可以有行为。更好的全方位。