Usage
Sometimes an object will have a property that can only take a limited set of values, such as male/female. You could simply use a String to represent those values, but you could also use int values. Using Strings may lead to errors. Using int values could lead to errors but will also make the code more difficult to read.
With enumerations we can specify male/female values as Gender.Male and Gender.Female. Enumerations will let you obtain String and numeric representations of these values if that is what you need at some point in your application.
Declaration
The simplest declaration would be something like this:
public enum Gender{
Male, Female;
}
But in addition to declaring final values, an enumeration can have a constructor and can also have methods:
public enum Gender{
Male("Masculino"), Female("Femenino");
private String spanish;
// the constructor
Gender(String spanish){
this.spanish = spanish;
}
// a method
public String toSpanish(){
return this.spanish;
}
}
This Gender enumeration could be used as follows:
Person p = new Person();
p.setGender(Gender.Male);String text = "The person's gender in Spanish is: " + p.getGender().toSpanish();
You can think of an enumeration as a Collection for which the JVM initializes all the collection objects and for which additions and removals are not allowed at run time. These collection objects are accessed statically.
In the example above Gender is the collection and its elements are accessed without having to instantiate Gender.