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.
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!
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
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:
Or, you make sure your methods accept only the contract, and not the implementation:
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 ofMyContract
!