Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java enums over Constants [duplicate]

Tags:

java

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?

like image 913
Anand Avatar asked Jan 16 '12 19:01

Anand


2 Answers

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.

like image 72
Joe Avatar answered Sep 30 '22 15:09

Joe


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.

like image 36
Vladimir Ivanov Avatar answered Sep 30 '22 17:09

Vladimir Ivanov