Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Interface cannot have protected methods [duplicate]

Tags:

java

Possible Duplicate:
Protected in Interfaces

In Java why cant I have protected methods in an interface?

Since according to Java specifications

protected access (denoted by the keyword protected) - a field or method accessible to any type in the same package, and to subclasses in any package.

If at all I have to use the interface, I am going to implement it and override the methods. So if I am going to implement where the class has access to those methods, since method accessible to in any package. So whats the harm in declaring the method as protected in Interface ?

like image 638
Lolly Avatar asked Jan 28 '12 14:01

Lolly


People also ask

Why interface Cannot have protected methods?

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.

Can an interface have protected methods?

Protected members of an interface In general, the protected members can be accessed in the same class or, the class inheriting it. But, we do not inherit an interface we will implement it. Therefore, the members of an interface cannot be protected.

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.

Can we have protected method in interface Java?

The java language specification doesn't currently allow the protected modifier for interface methods.


2 Answers

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.

like image 126
Sergey Kalinichenko Avatar answered Sep 21 '22 15:09

Sergey Kalinichenko


The interface of an object is the part of that object that is visible to external users of that class. On the contrary, protected and private methods (and fields) belong to the class internals. They are encapsulated inside the class and a class user should not be aware of them.

So, since interface is used to define interfaces (no pun intended), it is reasonable that they do not contain protected methods.

One doesn't want to think of implementation when defining an interface

like image 29
Vincenzo Pii Avatar answered Sep 24 '22 15:09

Vincenzo Pii