I have a scenario in which I have Player types ARCHER
,WARRIOR
, and sorcerer
.
What should I use in Player class for a player type?
Constant final static String variable or an Enum? and Why?
Please help with reasons.
Java – Why use Enums instead of Constants? Which is better in terms of software design and readability
androidenumsjava
Related Topic
- Java – Why use getters and setters/accessors
- Java – When to use static methods
- Java – Jackson with JSON: Unrecognized field, not marked as ignorable
- Java – What are enums and why are they useful
- Java – Where to get “UTF-8” string literal in Java
- Java: using switch statement with enum under subclass
- Java enum – why use toString instead of name
- R – Set the Culture for an asp.net RangeValidator
Best Answer
Suppose you use constant strings (or
int
values - the same goes for them):then you end up not really knowing the type of your data - leading to potentially incorrect code:
If you use enums, that would end up as:
Likewise, enums give a restricted set of values:
vs
Additionally, enums in Java can have more information associated with them, and can also have behaviour. Much better all round.