Question

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?

Was it helpful?

Solution

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

OTHER TIPS

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.

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top