Reputation: 21
Difference between accessing an object’s methods with an object reference vs an interface reference, even if both refer (point) to the same object.
I dont know what is object referene and interface reference please explain?
Upvotes: 1
Views: 2628
Reputation: 3
It's actually very simple. When you access object methods, with interface reference you can only access the methods that are part of that interface definition which are implemented by that object's class.
And when you access them with class reference then you can access all that are part of the class.
Actually with interface you don't care what is the actual class of that object, you only want to be concerned with the interface methods, that are implemented in that class, so you can access only those..
Upvotes: 0
Reputation: 1590
One case is when you know the type of your object (so the class your object is an instance of) and this way you can access all its methods. Let me stress that again: you know the class of the object.
Second case is when you only know that your object implements an interface, you do not know which class your object is. This way you only have access to the methods that the class inherits from that particular interface, and no other method.
Upvotes: 0
Reputation: 30097
If I understand you question correctly you are asking the difference between object of a class and object of an interface
Object of a class contains full implementation of the class. You will be able to call all the public methods and use public fields of that class through the class object.
On the other hand, interface object only exposes those methods and fields which are defined by interface.
Upvotes: 1
Reputation: 60714
If you have a reference to an object using an interface, you will only have access to that objects methods or properties that are defined in the interface. If you need to access any additional methods, you have to identify the specific type of the implementation, and cast it to that type before calling those methods or properties.
Using the interface type instead of the actual type is often done to reduce coupling between objects. For example, one of your objects that are logging something might need an instance of ILogger, but it should not really care if the implementation of ILogger logs to a file, to a web-service or does something else. It should only care about getting an object that fullfills the contract that the interface defines.
Upvotes: 3