Java Enumerations by Constants

Possible duplicate:
Understanding Enumerations in Java

Why should we use enums and not Java constants?

I read that Java enums provide type safety. Can someone please clarify this? Or is there another advantage to using enum over constants?

+4
source share
4 answers

To quote http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html :

public enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY } 

if you have this method:

 public EnumTest(Day day) { this.day = day; } 

you know that argument will always be day.

Compare with this:

 const int MONDAY = 1; const int TUESDAY = 2; const int CAT = 100; const int DOG = 101; 

you can pass something to this method:

 public EnumTest(int day) { this.day = day; } 

Using enum (or any type, such as a class or interface) gives you type safety: the type system ensures that you can only get the type you want. The second example is not type safe in this respect, because your method can take any int as an argument, and you don't know exactly what the value of int means.

Using an enumeration is a contract between the calling code and the called code that this value is of the specified type.

+9
source

Do you have animal ids:

 int DOG = 1; int CAT = 2; int COW = 3; 

And the variable:

 int animal; 

This is normal as long as you only work with these three numbers. But if you are mistaken, the compiler can check this out for you if you write

 animal = 5; 

And you do not see error two. Enumerations provide you with a better approach.

 public enum Animal { Dog, Cat, Cow } Animal animal = Animal.Dog; 

Now you have type safety.

+5
source

Another, but implicit difference is that the enumerations can have logic inside themselves, that is, they can have ctor and methods.

+1
source

One reason, besides type safety (already mentioned), is that enumerations have methods that mean code that uses constants heavily can migrate to the enum class itself (either a dynamic or a static method).

0
source

Source: https://habr.com/ru/post/1391309/


All Articles