Method Overloading with Overloaded Methods That Use Different Parameter Types, Including Enum and Varargs in Java


Write a Java program to demonstrate method overloading with overloaded methods that use different parameter types, including enum and varargs

  • The CurrencyConverter class contains two overloaded convert methods: one that converts a single amount from one currency to another, and another that converts multiple amounts and returns the total converted amount.
  • The first convert method takes the source currency, target currency, and amount to convert. In the provided code, it returns 0.0, indicating that the currency conversion logic needs to be implemented.
  • The second convert method takes the source currency, target currency, and a variable number of amounts to convert. It iterates through each amount and calls the first convert method to convert it, then adds up the converted amounts to get the total.
  • In the Main class, an instance of CurrencyConverter is created.
  • The convert method is called twice, once with a single amount to convert and once with multiple amounts.
  • As the conversion logic is not implemented and the default return value of 0.0 is used, the output shows the converted amounts as 0.0. The actual conversion logic should be implemented in the convert method to obtain correct results.

Source Code

enum Currency
{
	USD, EUR, GBP
}
 
class CurrencyConverter
{
	double convert(Currency from, Currency to, double amount)
	{        
		return 0.0; // Implement currency conversion logic here
	}
 
	double convert(Currency from, Currency to, double... amounts)
	{
		double total = 0.0;
		for (double amount : amounts)
		{
			total += convert(from, to, amount);
		}
		return total;
	}
}
 
public class Main
{
	public static void main(String[] args)
	{
		CurrencyConverter converter = new CurrencyConverter();
		double amount1 = converter.convert(Currency.USD, Currency.EUR, 100.0);
		double totalAmount = converter.convert(Currency.USD, Currency.EUR, 50.0, 75.0, 125.0);
		System.out.println("Converted Amount : " + amount1);
		System.out.println("Total Converted Amount : " + totalAmount);
	}
}

Output

Converted Amount : 0.0
Total Converted Amount : 0.0

Example Programs