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.
Advantages of enum: enum improves type safety at compile-time checking to avoid errors at run-time. enum can be easily used in switch. enum can be traversed. enum can have fields, constructors and methods.
Enums are lists of constants. When you need a predefined list of values which do represent some kind of numeric or textual data, you should use an enum. You should always use enums when a variable (especially a method parameter) can only take one out of a small set of possible values.
The only difference is that enum constants are public , static and final (unchangeable - cannot be overridden). An enum cannot be used to create objects, and it cannot extend other classes (but it can implement interfaces).
Enums are used when we know all possible values at compile-time, such as choices on a menu, rounding modes, command-line flags, etc. It is not necessary that the set of constants in an enum type stay fixed for all time. In Java (from 1.5), enums are represented using enum data type.
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";
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!
Additionally, enums in Java can have more information associated with them, and can also have behaviour. Much better all round.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With