DEV Community

Discussion on: ELI5: Why cast to an interface?

Collapse
 
alephnaught2tog profile image
Max Cerrina

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

Collapse
 
hamzaop profile image
Hamza

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.

Thread Thread
 
lluismf profile image
Lluís Josep Martínez

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

Collapse
 
dubyabrian profile image
W. Brian Gourlie • Edited

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!