Wednesday, September 14, 2011

Enum

Since version 1.5.0, Java introduced enum as a special kind of class. It lets us to rewrite our static final constants to enum class. Here is a simple example:

public enum OrderStatus {
NEW,
COMPLETE,
BILLING_FAILED,
SHIPPED;
}

It is pretty straightforward, isn't it? Now lets put constructor, methods, and variables in it:

public enum OrderStatus {

NEW(20),
COMPLETE(100),
BILLING_FAILED(-1),
SHIPPED(80);

private int percent;

private OrderStatus(int paramPercent) {
this.percent = paramPercent;
}

public int getPercent() {
return percent;
}

}

Now what happens if we print it on console?

System.out.println(OrderStatus.NEW.name()); // this will print NEW
System.out.println(OrderStatus.NEW.getPercent()); // this will print 20
System.out.println(OrderStatus.NEW.ordinal()); // this will print 0

Note that the first statement must be the constant (NEW, COMPLETE, etc in our example), otherwise the compiler will generate error messages. In addition, the constructor can't be declared as public (that's why I declare it as private).

To get a list of all constants of the enum we can use OrderStatus.values() and it will return an array of {NEW, COMPLETE, BILLING_FAILED, SHIPPED} in that order.

0 comments:

 

©2009 Stay the Same | by TNB