How do I use the enum type with a constructor?
Author: Deron Eriksson
Description: This Java tutorial describes how to use the enum type with a constructor that initializes an instance field.
Tutorial created using: Windows XP || JDK 1.6.0_10


A JavaSW enum type can have a private constructor that can be used to initialize instance fields. The EnumDemo class demonstrates this. It features a Food enum type with four constants: HAMBURGER, FRIES, HOTDOG, and ARTICHOKE. Notice that after each constant a value is present in parentheses. This calls the constructor for that member to initialize the price field for that member. Thus, each food constant has a different price.

We iterate over the Food values in the for loop in the main() method. In this method, we first display the name of the food constant. Next we examine the price for that food item and display whether the price is expensive or affordable. Following this, for fun, we demonstrate the use of a switch statement with the Food enum type.

EnumDemo.java

package cakes;

public class EnumDemo {

	public enum Food {
		HAMBURGER(7), FRIES(2), HOTDOG(3), ARTICHOKE(4);

		Food(int price) {
			this.price = price;
		}

		private final int price;

		public int getPrice() {
			return price;
		}
	}

	public static void main(String[] args) {
		for (Food f : Food.values()) {
			System.out.print("Food: " + f + ", ");

			if (f.getPrice() >= 4) {
				System.out.print("Expensive, ");
			} else {
				System.out.print("Affordable, ");
			}

			switch (f) {
			case HAMBURGER:
				System.out.println("Tasty");
				continue;
			case ARTICHOKE:
				System.out.println("Delicious");
				continue;
			default:
				System.out.println("OK");
			}
		}

	}

}

The console output for EnumDemo is shown here:

Console output from executing EnumDemo

Food: HAMBURGER, Expensive, Tasty
Food: FRIES, Affordable, OK
Food: HOTDOG, Affordable, OK
Food: ARTICHOKE, Expensive, Delicious