为什么使用枚举,而不是常量? [英] Why use Enums instead of Constants?

查看:179
本文介绍了为什么使用枚举,而不是常量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一种情况中,我有播放器类型的射手,战士,和巫师。我应该在播放器类我用?类型或枚举一个字符串变量?为什么枚举,为什么常量字符串。请帮助的原因。

I have a scenario in which I have Player types ARCHER,WARRIOR, and sorcerer. What should I use in player class? A String variable for type or a Enum? Why enum and why Constant Strings. Please help with reasons.

推荐答案

假设你使用常量字符串(或 INT 值 - 这同样适用于他们):

Suppose you use constant strings (or int values - the same goes for them):

// 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";

那么你最终没有真正了解你的数据的类型 - 导致潜在的不正确code:

then you end up not really knowing the type of your data - leading to potentially incorrect code:

String playerType = Constants.MALE;

如果您使用枚举,这将最终为:

If you use enums, that would end up as:

// Compile-time error - incompatible types!
PlayerType playerType = Gender.MALE;

同样,枚举给受限制的组值:

Likewise, enums give a restricted set of values:

String playerType = "Fred"; // Hang on, that's not one we know about...

VS

PlayerType playerType = "Fred"; // Nope, that doesn't work. Bang!

此外,在Java中枚举可以具有与它们相关联的详细信息,并且也可以有行为。好多全面。

Additionally, enums in Java can have more information associated with them, and can also have behaviour. Much better all round.

这篇关于为什么使用枚举,而不是常量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆