if we cast an object to an interface, won’t this object be able to call its own methods? in the following example, myObj will only be able to call MyInterface methods?
MyInterface myObj = new Obj();
If this is correct, what is the difference between those 2 objects :
MyInterface myObj = new Obj();
MyInterface mySec = new Sec();
Thanks for your help
For this to be legal, both
ObjandSecwill have to be implementers ofMyInterface. The difference between these two objects would be how they provide that implementation.ObjandSeccould do two very different or very similar things, but their commonality is that they would adhere to a contract that you could rely upon. Consider you have a methodEach object,
myObjandmySec, could be passed into this method, and this method could then use that object’sfrobmethod (assuming frob is part of the interface declaration). This is liberating. This allows you to do very powerful things, by programming to interfaces and not to implementations. For example, you can extend functionality of classes and not change a line of code in those classes, you simply pass a different implementation of a dependency. You are not tied to, or coupled with, any one implentation inside the methoddoSomethingWith.Internally, instances of
Objwill continue to have full access to theObjAPI.myObjis still anObj, it will always be able to use its own implementation details.Instances of
Objwill still be instances ofObj, and those instances will still be able to usedoFrobbing. Externally, persons using those instances via the interface reference will only be able to access the interface methods.