DEV Community

Discussion on: ELI5: Why cast to an interface?

Collapse
 
evanoman profile image
Evan Oman • Edited

Casting to an interface allows you to pass/refer to objects with the same behavior.

For example, if you wanted to make a report from a bunch of forecasts you could write code like this:

/* Collect some forecastable things */
List<Forecastable> forecastables = Arrays.asList(nycWeather,frankfurtWeather, nyse, dax);

/* Get the forecasts themselves */
List<Forecast> forecasts = forecastables.stream()
    .map(Forecastable::getForecast)
    .collect(Collectors.toList());

/* Add the forecasts to our report */
report.addForecasts(forecasts);

Here you can see that we only need the Forecastable subset of these objects' functionality so we cast them to the interface.