I will give an example from .NET.
ConcurrentDictionary<TKey, TValue> : IDictionary<TKey, TValue>, IDictionary
Here you can see ConcurrentDictionary implementing dictionary interfaces. However I can’t access Add<TKey,TValue> method from a ConcurrentDictionary instance. How is this possible?
IDictionary<int, int> dictionary = new ConcurrentDictionary<int, int>();
dictionary.Add(3, 3); //no errors
ConcurrentDictionary<int, int> concurrentDictionary = new ConcurrentDictionary<int, int>();
concurrentDictionary.Add(3, 3); //Cannot access private method here
Update:
I know how I can access it but I didn’t know explicitly implementing an interface could allow changing access modifiers to internal. It still doesn’t allow making it private though. Is this correct? A more detailed explanation about that part would be helpful. Also I would like to know some valid use cases please.
It is implemented as an explicit interface implementation, meaning you need a variable of the
IDictionary<TKey, TValue>type to access it.See the documentation of
ConcurrentDictionary<TKey, TValue>, under the Explicit Interface Implementations section.If you cast the concurrent dictionary to
IDictionary<TKey, TValue>, you will be able to callAddon it.No, this is not correct.
Explicit interface implementations do not change the access modifiers. They change how you can access the members that were implemented that way (i.e. require you to use a variable of the interface type). They are still public members, but can only be accessed using the interface type, not the implementing type.