ELI5: Why cast to an interface?

So, I am super new to OOP and Java–specifically, just finishing up my first semester of it.

I understand interfaces are akin to contracts, and understand the uses of them; similarly, I understand casting, etc. I understand you can cast to an interface, but I don’t get why you would want to. I’ve checked a number of books, a number of sites, read some arguments on the topic on SO, and have yet to actually get the point of doing so.

Specifically: if you had an interface called Forecastable and two classes, Weather and StockMarket, both of which implemented Forecastable–and thus must have the methods of the interface, and thus any object instantiated in them has access to those methods by definition–then what would the actual use be of casting either some Weather or StockMarket object be to Forecastable, if they can both already access those methods inherently?

原文链接:ELI5: Why cast to an interface?

© 版权声明
THE END
喜欢就支持一下吧
点赞5 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容