When I implement an interface
method, I am forced to make it a public
method.
We may have cases where we want to use either the default
(like in case of access within the same package) or protected
.
Can anyone please explain the reason behind this limitation?
Interface methods are implicitly public in C# because an interface is a contract meant to be used by other classes. In addition, you must declare these methods to be public, and not static, when you implement the interface.
The Interface BodyAll abstract, default, and static methods in an interface are implicitly public , so you can omit the public modifier. In addition, an interface can contain constant declarations. All constant values defined in an interface are implicitly public , static , and final .
Protected methods are intended for sharing implementation with subclasses. Interfaces have nothing to offer as far as implementation sharing goes, because they have no implementation at all. Therefore all methods on interfaces must be public.
1) Interface members are only visible to code outside of the interface based on the rules of the respective visibility level. public : Interface members in C# are public by default, so this works.
Interfaces are meant to define the public API of a type - and only that, not its implementation. So any method (or static member) you define in an interface is by definition public
.
Since an interface can't contain any concrete implementation, there is no way to call any member methods from within. And declaring such methods but leaving the calls to them to subclasses or totally unrelated clients would mean your type definition is incomplete and brittle. That is why if you need to define protected or package access members, you can do so in an abstract class (which may also contain implementation).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With