Enum
A useful new feature of Java 5.0
Enum is a useful new feature of Java 5.0. An Enum in Java stands for Enumeration. There are many entities that have fixed properties and belong in a group. Such entities may be represented as fields in a Java Enum class - a class whose fields (properties) are constants. For example, the months in a year may be represented as an Enumeration. Conventionally, enum fields are always represented in uppercase letters as they are constants (in Java coding convention constants are represented by uppercase letters). Enums in Java are very flexible and powerful because they allow developers to model objects within them.
If we find that only five fruits would ever be used in the application for which the Fruits.java file was written, we could represent the five fruits in an enumeration as an alternative to Fruits.Java. Obviously, an Enum is not very suitable to a group like fruits because of the large size of the set of fruits. Enums are best used to represent sets like months and days of the week that consist of a small number of elements. The following is a simple example of declaring and using an Enum in a scenario where only five fruits are used. While we have simply used a getCalories method, a real life enum may contain many useful methods. For example, an enum that represents the twelve months of the calendar may contain methods that calculate the number of days in each month, the number of weekends in a month given a certain year and so on. FruitEnum.java includes descriptive comments:
public enum FruitEnum {
// Declaring the five constant fields of the FruitEnum.
// GetArray converts comma-delimited string to a String Array
APPLE ("Apple",getArray("yellow,red,green"),"apple.jpeg",75),
ORANGE ("Orange", getArray("orange"),"orange.jpeg",60),
MANGO ("Mango", getArray("yellow,green"),"mango.jpeg",120),
BANANA ("Banana", getArray("yellow,green"),"banana.jpeg",120),
GUAVA ("Guava", getArray("yellow"),"guava.jpeg",120);
//The fields in each constant
final String name;
final String[] color;
final String image;
final int calories;
// A method that will load the list of arrays into the Enum's second
// parameter for construction
private static String[] getArray(String color)
{
return color.split(",");
}
// This is where the members of the enum are constructed
FruitEnum(String name,String[] color,String image,int calories) {
this.name = name;
this.color = new String[color.length];
System.arraycopy(color,0,this.color,0,color.length);
this.image = image;
this.calories = calories;
}
// A simple method for this enum
String getNameCalories() {
return "Fruit Name: " + name + ", Calories: " + calories;
}
// Main method calls getNameCalories for each Enum member (using
// FruitEnum.values()
public static void main(String[] args) {
System.out.println("Our Fruits and Calorific Contents");
for (FruitEnum f : FruitEnum.values())
System.out.printf( f.getNameCalories()+"%n");
}
}