Method Overloading with Overloaded Methods That Use Different Parameter Types, Including Enums in Java


Create a Java program to demonstrate method overloading with overloaded methods that use different parameter types, including enums

  • The Color enum defines three constants: RED, GREEN, and BLUE.
  • The EnumManipulator class contains two displayColor methods: one that accepts a single Color and another that accepts an array of Color.
  • The first displayColor method displays the name of the selected color using the name() method of the enum constant.
  • The second displayColor method displays the names of all selected colors in the array by iterating over each color and appending its name to a StringBuilder with a newline separator. It then trims the result to remove any leading or trailing whitespace.
  • In the Main class, an instance of the EnumManipulator class is created.
  • The displayColor method is called twice, once with a single Color and once with an array of Color.
  • In each case, the appropriate displayColor method is invoked based on the argument types, and the result is printed.

Source Code

enum Color
{
	RED, GREEN, BLUE
}
 
class EnumManipulator
{
	String displayColor(Color color)
	{
		return "Selected color : " + color.name();
	}
 
	String displayColor(Color[] colors)
	{
		StringBuilder result = new StringBuilder();
		for (Color color : colors)
		{
			result.append("\nSelected color : ").append(color.name()).append(" ");
		}
		return result.toString().trim();
	}
}
 
public class Main
{
	public static void main(String[] args)
	{
		EnumManipulator manipulator = new EnumManipulator();
		System.out.println(manipulator.displayColor(Color.GREEN));
		Color[] colorArray = {Color.RED, Color.BLUE, Color.GREEN};
		System.out.println(manipulator.displayColor(colorArray));
	}
}

Output

Selected color : GREEN
Selected color : RED 
Selected color : BLUE 
Selected color : GREEN

Example Programs