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

霸气de小男生 提交于 2019-11-28 06:16:19

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

npinti

Maybe this will provide some answers.

To my knowledge, you use interfaces to allow people from outside your code to interact with your code. To do this, you need to define your methods public.

If you would like to force someone to override a given set of private methods, you might want to declare an abstract class with a series of abstract protected methods.

nist

An interface is a contract that the class that implements it will have the methods in the interface. The interface is used to show the rest of the program that this class has the methods and that they could be called

EDIT: This answer is meant for C# interface implementations. In this case of Java the scenario is similar just that the syntactic analyzer wants a public keyword mentioned in the interface, which is implicitly done in C#

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.

interface IStorable
{
     void Read( );
     void Write(object obj);
}

Notice that the IStorable method declarations for Read( ) and Write( ) do not include access modifiers (public, protected ..). In fact, providing an access modifier generates a compile error.

class Document : IStorable
{
     public void Read( )
     {
         //
     }
     public void Write(object obj)
     {
         //
     }
}

Just think about interfaces as Contracts to be implemented as public

  1. If we mark a interface method as private the implementing class wont see the method and cant override it.

  2. If we mark a interface method as protected the implementing class wont see the method unless it is in the same package as the interface.

  3. If we mark a interface method without any access modifier the
    implementing class wont see the method unless it is in the same
    package as the interface

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!