How to customized a value with Enum in Java

By default enums have their own string values, we can also assign some custom values to enums. Consider below example for that.

Examples:

enum  Fruits
{
    APPLE(“RED”), BANANA(“YELLOW”), GRAPES(“GREEN”);
}

In the above example, we can see that the Fruits enumeration has three members, namely APPLE, BANANA and GRAPES, which have their own different custom values ??RED, YELLOW and GREEN.

Now to use this enum in code, there are some points we have to follow:-

  1. We must create a parameterized constructor for this enumeration class. Why? Because we know that objects of enumeration classes cannot be created explicitly, we use parameterized constructors for initialization. And the constructor cannot be public or protected, it must have private or default modifiers. Why? If we create public or protected, it will allow multiple objects to be initialized. This completely violates the concept of enumeration.
  2. We must create a getter method to get the value of the enumeration.

 

// Java program to demonstrate how values can
// be assigned to enums.
enum TrafficSignal
{
	// This will call enum constructor with one
	// String argument
	RED("STOP"), GREEN("GO"), ORANGE("SLOW DOWN");

	// declaring private variable for getting values
	private String action;

	// getter method
	public String getAction()
	{
		return this.action;
	}

	// enum constructor - cannot be public or protected
	private TrafficSignal(String action)
	{
		this.action = action;
	}
}

// Driver code
public class EnumConstructorExample
{
	public static void main(String args[])
	{
		// let's print name of each enum and there action
		// - Enum values() examples
		TrafficSignal[] signals = TrafficSignal.values();

		for (TrafficSignal signal : signals)
		{
			// use getter method to get the value
			System.out.println("name : " + signal.name() +
						" action: " + signal.getAction() );
		}
	}
}

Output:

name : RED action: STOP
name : GREEN action: GO 
name : ORANGE action: SLOW DOWN 

 

Submit Your Programming Assignment Details