DEV Community

Discussion on: ELI5: Why cast to an interface?

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!