Creating Enum variables

13 February 2012 By Nithya Vasudevan 819 views No Comment
0 Flares Twitter 0 Facebook 0 Google+ 0 0 Flares ×

Even though enum is a class type, we do not use new keyword but create a variable just like a primitive type as follows.

PizzaSize size;
PizzaSize size = PizzaSize.LARGE;

The main advantage of using enums when compared to using constants, created by static and final keywords, is that only the values defined in the enumeration can be assigned. This is because each enum constant is of the same type as enum and hence values other than defined in enum give compile time errors.

In the above example, SMALL, MEDIUM, and LARGE are the only values of type ‘PizzaSize’. Hence the variable ‘size’ can take only those values, other values cause type mismatch.

This is how enums solve the bad/illegal assignment problem.

package com.ibytecode.enums;

public class Pizza {

	enum PizzaSize
	PizzaSize size;

	public static void main(String[] args) {
		Pizza pizza = new Pizza();
		pizza.size = PizzaSize.LARGE;



Tags: , , , , , ,