Wednesday, September 30, 2009

Why Enum in Java

If you use Java1.5, there is a feature declaring constant value i.e Enum. An Enumerated type defines a finite set of symbolic names and their values. These symbolic names are called enum constants or named constants.

Well, you can declared such constants by static final variable like:


public class MyConstants
{
public static final int BUSY = 1;
public static final int IDLE = 2;
public static final int BLOCKED = 3;
}


such constants are not typesafe, as any int value can be used where we need to use a constant declared in the MyConstants class. Such a constant must be qualified by the class name. When such a constant is printed, only its value is printed, but we unable to print its name. One important thing is that, if you want to modify the value of any constant, then you have to compile both, the class or interface that declare the constant and the class where this constants are used. This is required bkz, constant names are substituted by its value at compile time.

Please look the code Snippet for the approach outlined above.

public enum ConstantEnum {
BUSY(3),IDLE(2);

int data;
private ConstantEnum(int refValue) {
data = refValue;
}

public int getValue()
{
return data;
}
}

public class TestValue {
public static void main(String arg[])
{
int i= ConstantEnum.BUSY.getValue();
System.out.println("using Enum value :"+ConstantEnum.BUSY);
System.out.println("using static final :"+MyConstants.BUSY);
}
}

No comments:

Post a Comment