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.
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
!