The responsibility of the visibility of a method is relegated to the class that implements the interface.
public interface IMyInterface
{
bool GetMyInfo(string request);
}
In C# set access modifier public, private or protected before the method GetMyInfo() generates the following error: The modifier 'private' is not valid for this item.
Is there a reason you can not define the access modifier on a method or in an interface?
(Question already asked in french here)
You can actually make the method private in the implementing class, if you make an explicit interface implementation:
This approach means that
GetMyInfo
will not be part of the public interface ofMyClass
. It can be accessed only by casting aMyClass
instance toIMyInterface
:So, in the context of the interface, all its members will be public. They can be hidden from the public interface of an implementing class, but there is always the possibility to make a type cast to the instance and access the members that way.
In terms of OO - encapsulation is all about data hiding. That means whatever goes on inside a class is up to the class implementation. Which means it would be useless to contractually enforce private members.
However, the reason one uses interfaces is because you want to ensure a class adheres to a specific contract and exposes several public members in a consistent way.
All of the methods of an interface must have the same access level - so that the caller may use all of them. However interfaces can also be internal (or as nested interface private).
If you need different access levels use a distinct interface.
A private definition in the interface would:
The interface defines a contract between an object and clients that call its members. A private method cannot be accessed by any other objects so it doesn't make sense to add it to the interface. All members of an interface are considered public for this reason.