5

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?

Community
  • 1
  • 1
Anand
  • 20,708
  • 48
  • 131
  • 198

4 Answers4

11

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.

Joe
  • 46,419
  • 33
  • 155
  • 245
5

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.

Vladimir Ivanov
  • 42,730
  • 18
  • 77
  • 103
1

Another, yet unmentioned difference is that enums can have logic inside them, i.e., can have ctor and methods.

Victor Sorokin
  • 11,878
  • 2
  • 35
  • 51
0

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).

Amir Afghani
  • 37,814
  • 16
  • 84
  • 124