Java Enumerations

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.

Switch Statement Using Enumerations
If you use enumerations, sooner or later you will have the need to control program logic based on an enum value through a switch statement. The following code illustrates a switch statement using a TransportMode enumeration with values Air, Ocean, and Truck.

	private void processMode(TransportMode mode) {
		switch (mode) {
		case Air:
			// Do something here for Air
			break;
		case Ocean:
			// Do something here for Ocean
			break;
		case Truck:
			// Do something here for Truck
			break;
		default:
			// You will never reach this point.
			// The statement will throw a NullPointerException if mode == null
		}
	}

If you use Eclipse, code completion will help you write the statement by pressing Control-Space after “case “:

Eclipse code completion

6 comments to Java Enumerations

You must be logged in to post a comment.