Interfaces for Custom Temperature Conversion in Java


Write a Java program to demonstrate the use of an interface for custom temperature conversion

  • The TemperatureConverter interface declares two methods: celsiusToFahrenheit for converting Celsius to Fahrenheit and fahrenheitToCelsius for converting Fahrenheit to Celsius.
  • In the main method of the Main class, an anonymous class is created that implements the TemperatureConverter interface.
  • Inside the anonymous class, the celsiusToFahrenheit and fahrenheitToCelsius methods implement the logic for temperature conversion.
  • Sample Celsius and Fahrenheit values are provided.
  • The celsiusToFahrenheit method is called to convert Celsius to Fahrenheit, and the result is printed.
  • The fahrenheitToCelsius method is called to convert Fahrenheit to Celsius, and the result is printed.

Source Code

interface TemperatureConverter
{
	double celsiusToFahrenheit(double celsius);
	double fahrenheitToCelsius(double fahrenheit);
}
 
public class Main
{
	public static void main(String[] args)
	{
		TemperatureConverter temperatureConverter = new TemperatureConverter()
		{
			@Override
			public double celsiusToFahrenheit(double celsius)
			{                
				return (celsius * 9/5) + 32; // Implement Celsius to Fahrenheit conversion
			}
 
			@Override
			public double fahrenheitToCelsius(double fahrenheit)
			{               
				return (fahrenheit - 32) * 5/9; // Implement Fahrenheit to Celsius conversion
			}
		};
 
		double celsiusValue = 25.0;
		double fahrenheitValue = 77.0;
 
		// Convert Celsius to Fahrenheit
		double fahrenheitResult = temperatureConverter.celsiusToFahrenheit(celsiusValue);
		System.out.println(celsiusValue + "°C is " + fahrenheitResult + "°F");
 
		// Convert Fahrenheit to Celsius
		double celsiusResult = temperatureConverter.fahrenheitToCelsius(fahrenheitValue);
		System.out.println(fahrenheitValue + "°F is " + celsiusResult + "°C");
	}
}

Output

25.0°C is 77.0°F
77.0°F is 25.0°C

Example Programs