Interfaces for Custom Currency Conversion in Java


Create a Java program to demonstrate the use of an interface for custom currency conversion

  • The CurrencyConverter interface declares a method convertCurrency for converting currency.
  • In the main method of the Main class, an anonymous class is created that implements the CurrencyConverter interface.
  • Inside the anonymous class, the convertCurrency method implements the currency conversion logic. For simplicity, the code returns the same amount without any conversion.
  • A sample amount, source currency, and target currency are provided.
  • The convertCurrency method of the CurrencyConverter interface is called to demonstrate currency conversion.

Source Code

interface CurrencyConverter
{
	double convertCurrency(double amount, String fromCurrency, String toCurrency);
}
 
public class Main
{
	public static void main(String[] args)
	{
		CurrencyConverter currencyConverter = new CurrencyConverter()
		{
			@Override
			public double convertCurrency(double amount, String fromCurrency, String toCurrency)
			{
				// Implement currency conversion logic here
				// For simplicity, we'll return the same amount without conversion
				return amount;
			}
		};
 
		double amount = 25000.0;
		String fromCurrency = "USD";
		String toCurrency = "EUR";
 
		double convertedAmount = currencyConverter.convertCurrency(amount, fromCurrency, toCurrency);
		System.out.println("Converted Amount : " + convertedAmount + " " + toCurrency);
	}
}

Output

Converted Amount : 25000.0 EUR

Example Programs