Possible Duplicate:
Understanding Enums in Java
Why should we use enums rather Java constants?
I have read that Java enums gives type safety. Can somebody please elaborate it? Or there is any other advantage of using enum over constants?
Possible Duplicate:
Understanding Enums in Java
Why should we use enums rather Java constants?
I have read that Java enums gives type safety. Can somebody please elaborate it? Or there is any other advantage of using enum over constants?
To quote http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html:
public enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, SATURDAY
}
when you have this method:
public EnumTest(Day day) {
this.day = day;
}
you know that the argument is always going to be a day.
Compare to this:
const int MONDAY = 1;
const int TUESDAY = 2;
const int CAT = 100;
const int DOG = 101;
you could pass anything to this method:
public EnumTest(int day) {
this.day = day;
}
Using an enum
(or any type, such as a class or interface) gives you type safety: the type system makes sure you can only get the kind of type you want. The second example is not type safe in that regard, because your method could get any int as an argument, and you don't know for sure what the int value means.
Using the enum is a contract between the calling code and the code being called that a given value is of a given type.
Image you have animals ids:
int DOG = 1;
int CAT = 2;
int COW = 3;
And a variable:
int animal;
It is ok while you operate only with 3 these numbers. But if you mistake, then compiler can check that for you, if you write
animal = 5;
And you don't see the mistake two. Enums provide you a better approach.
public enum Animal {
Dog,
Cat,
Cow
}
Animal animal = Animal.Dog;
Now you have type safety.
Another, yet unmentioned difference is that enums can have logic inside them, i.e., can have ctor and methods.
One reason aside from type safety (already mentioned) is that enums have methods, meaning code that makes heavy use of the constants could migrate to the enum class itself (either dynamic or static method).