Java 5.0 Enums – constant-specific methods

I recently used Java 5.0 Enums to represent directions in a compact way. The ese methods in the Enum are called constant-specific methods. Apart from type-safety they also provide constant-specific behaviour.


/*
* Enum representing the current direction and its left and right
* directions.
*/


public enum EnumDirection {


SOUTH( 1, "SOUTH" ){
public EnumDirection turnLeft() {
return EAST;
}


public EnumDirection turnRight() {
return WEST;
}
},


EAST( 2, "EAST" ){
public EnumDirection turnLeft() {
return NORTH;
}


public EnumDirection turnRight() {
return SOUTH;
}
},


NORTH( 0, "NORTH" ) {
public EnumDirection turnLeft() {
return WEST;


}
public EnumDirection turnRight() {
return EAST;
}
},
WEST( 3, "WEST" ){


public EnumDirection turnLeft() {
return SOUTH;
}
public EnumDirection turnRight() {
return NORTH;
}

};


public abstract EnumDirection turnLeft();


public abstract EnumDirection turnRight();


private String direction;


private int number;


EnumDirection( int number, String direction ) {
this.direction = direction;
this.number = number;
}


public String getDirection(){
return direction;
}


public String getDescription( ) {
switch( this ) {
case NORTH: return "NORTH";
case SOUTH: return "SOUTH";
case EAST: return "EAST";
case WEST: return "WEST";
default: return "Unknown Direction";
}

}


public static EnumDirection getDirection( int number ) {
switch( number ) {
case 0:
return EnumDirection.NORTH;
case 1:
return EnumDirection.SOUTH;
case 2:
return EnumDirection.EAST;
case 3:
return EnumDirection.WEST;
default:
return EnumDirection.EAST;
}

}


public void printString() {
System.out.printf("%s %d%n", NORTH, NORTH.direction);
System.out.printf("%s %d%n", SOUTH, SOUTH.direction);
System.out.printf("%s %d%n", EAST, EAST.direction);
System.out.printf("%s %d%n", WEST, WEST.direction);
}


public int getNumber() {
return number;
}


}

One Response to Java 5.0 Enums – constant-specific methods

  1. Pingback: Enum value matching using AspectJ « MindSpace

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: