Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I declare a public method in an interface?

Tags:

c#

.net

Why doesn't the compiler like that I declare a public method in a class interface (this caused the error I got here .NET Class Interface, Inheritance and Library: error does not implement interface member).

Is it just because of syntax or because of something more fundamental ?

OK it's implicit but why would it hurt to make it explicit ?

like image 272
user310291 Avatar asked Apr 20 '11 16:04

user310291


People also ask

Can we declare public method in 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 .

Can we use public in interface in Java?

Just like with classes, a Java interface can be declared public or package scope (no access modifier).

Can I define a method in interface?

There can be only abstract methods in the Java interface, not the method body. It is used to achieve abstraction and multiple inheritance in Java. In other words, you can say that interfaces can have abstract methods and variables. It cannot have a method body.

Why all methods in interface are 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.


1 Answers

Interface is a contract and anywhere where you can access the interface, you should be able to access all the methods in it. In other words, all the methods declared in the interface are supposed to be public so it doesn't make sense stating it explicitly.

like image 107
Bala R Avatar answered Oct 11 '22 02:10

Bala R