loading...

re: ELI5: Why cast to an interface? VIEW POST

TOP OF THREAD FULL DISCUSSION
re: If you cast to Forecastable, then that object can only access the methods of the interface, you can't access other methods in the Weather or StockM...
 

Okay, that makes sense. But why would you want to do that?

 

You can do that for example to check whether some class implements an interface at runtime with a try catch block, if the cast fails then you can throw an error saying that the class should implement the interface, one example is to make a callback between Activity and Fragment in Android.

This would be a programming error and you shouldn't use the Exception mechanism to catch errors.

 

One reason is that you want to ensure that no methods that aren't part of the contract are called on the object. If the interface represents a contract, yet you can call a method that isn't on the interface, in a sense, the contract has been broken!

I will say that it's somewhat odd to cast a type to accomplish this. Typically you would either instantiate an object of the interface type, for example:

MyContract contract = new MyContractImpl();

Or, you make sure your methods accept only the contract, and not the implementation:

void doSomething(MyContract contract) {
    ...
}

This way, even though the underlying type is a MyContractImpl, you won't be able to call methods on it that aren't a part of MyContract!

Code of Conduct Report abuse