Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should we declare interface methods as public? [duplicate]

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?

like image 591
Vishnu Avatar asked Mar 08 '12 08:03

Vishnu


People also ask

Why should we declare interface methods as public?

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.

Should interface methods be public?

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 .

Why interface methods are not protected?

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.

Why interface members are 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.


1 Answers

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).

like image 105
Péter Török Avatar answered Oct 08 '22 21:10

Péter Török