Understanding Enums in Java

As per java doc, an enum type is a type whose fields consist of a fixed set of constants. Common examples include compass directions (values of NORTH, SOUTH, EAST, and WEST) and the days of the week. Being constant the fields are in Uppercase.


Enums vs class of constant’s


Enum restrict you to a selected set of values whereas a constant class doesn’t, a variable can be assigned any value from any constant class or any values that is of same type.


Declaration of enum


Enums can be declared outside a class, also inside a class but not inside a method. A Enum declared outside a class can be declared with public or default modifier.

Following is an example of enum declared outside a class:

enum CoffeeSize {
// 8, 10 & 16 are passed to the constructor
BIG(8), HUGE(10), OVERWHELMING(16);
CoffeeSize(int ounces) {
this.ounces = ounces;
}
private int ounces;
public int getOunces() {
return ounces;
}
}
class Coffee {
CoffeeSize size;
public static void main(String[] args) {
Coffee drink1 = new Coffee();
drink1.size = CoffeeSize.BIG;
Coffee drink2 = new Coffee();
drink2.size = CoffeeSize.OVERWHELMING;
System.out.println(drink1.size.getOunces());
for(CoffeeSize cs: CoffeeSize.values()){
System.out.println(cs + " " + cs.getOunces());
}
}
}

Each enum value has an index associated with it. So the order of declaration matters.


Conceptualization of enums


You can think of enums as a class of constants as follows:

// conceptual example of how you can think
// about enums
class CoffeeSize {
String size;
public static final CoffeeSize BIG = new CoffeeSize("BIG", 0);
public static final CoffeeSize HUGE = new CoffeeSize("HUGE", 1);
public static final CoffeeSize XXL = new CoffeeSize("XXL", 2);
public CoffeeSize(String enumName, int index) {
size = enumName;
}
String getSize(){
return size;
}
public static void main(String[] args) {
System.out.println(CoffeeSize.BIG.getSize());
}
}

Output:
8
BIG 8
HUGE 10
OVERWHELMING 1


Code block to override defaults value for an enum


You can have code block to override defaults value for an enum. Lets say you have two methods—one for size and one for size name. Here we use code block to override common coffee size.

enum CoffeeSize {
BIG(30),
HUGE(34),
XXL(40) { // start a code block for this constant
public String getSizeName() {
// override the method defined in CoffeeSize
return "A";
}
}; // semicolon is REQUIRED when more code follows
CoffeeSize(int size) {
this.size = size;
}
private int size;
public int getSize() {
return size;
}
public String getSizeName() {
// this method is overridden by the XXL constant
return "B";
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *