Creating Enum variables

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;
(Or)
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
	{
		SMALL, MEDIUM, LARGE
	};
	
	PizzaSize size;

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

}

LARGE

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.