Interfaces for Custom Weather Information Retrieval in Java


Create a Java program to demonstrate the use of an interface for custom weather information retrieval

  • The WeatherService interface declares a method getWeatherInfo for retrieving weather information.
  • In the main method of the Main class, an anonymous class is created that implements the WeatherService interface.
  • Inside the anonymous class, the getWeatherInfo method implements the logic to retrieve weather information. In this example, a mock response is returned indicating sunny weather with a temperature of 25°C for the specified location.
  • A sample location is provided.
  • The getWeatherInfo method of the WeatherService interface is called to retrieve weather information for the specified location.
  • The retrieved weather information is printed to the console.

Source Code

interface WeatherService
{
	String getWeatherInfo(String location);
}
 
public class Main
{
	public static void main(String[] args)
	{
		WeatherService weatherService = new WeatherService()
		{
			@Override
			public String getWeatherInfo(String location)
			{
				// Implement weather information retrieval logic here (e.g., using a weather API)
				return "Weather in " + location + " : Sunny, 25°C";
			}
		};
 
		String location = "New York, USA";
 
		// Get weather information
		String weatherInfo = weatherService.getWeatherInfo(location);
		System.out.println(weatherInfo);
	}
}

Output

Weather in New York, USA : Sunny, 25°C

Example Programs