• Post Reply Bookmark Topic Watch Topic
  • New Topic

If interface can be default then why not protected?  RSS feed

 
Rish Gupta
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Q:
I was just wondering.. my understanding from everywhere I have read is interface cannot be private or protected (not at the top level) but when we declare an interface without any modifier it is default.
We know default modifier has more restricted access than protected.. public > protected > default > private
Now since an interface can be public and default then why not protected as clearly if they were allowed to be protected they could be implemented by a subclass..?

A:
While typing this question I figured how would an interface know which is it's subclass? that is why Java allows only public i.e. any class can implement it or default i.e. any class within the package can implement.. am I right?
 
Rish Gupta
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Now another question comes to mind.. say we have a scenario below:

package one
protected class oneA
{
}

protected interface oneB
{
}
//package one ends

package two
public class twoA extends oneA implements oneB
{
}


Can the above scenario be possible?
 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This isn't specific to interfaces. Top level classes can only have public or default access as well. Try it.

To understand why...look at it this way. How can a class implement an interface or extend a class if it can't already see the interface or class? If it's in a different package, in a manner of speaking your class would have to already be a subclass before it could become a subclass. So allowing protected in that position doesn't really make sense.
 
Rish Gupta
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
perfecto! thank you.
 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Rish Gupta wrote:perfecto! thank you.

It's possibly also worth mentioning that Java muddies the waters a bit by making protected items also visible to things in the same package, which is not the same as in some other languages (like C++). I suspect that doing it that way made things simpler internally, but it's not really the intent of the keyword in OOP terms, and I usually find it easiest to forget about that little "wrinkle".

Winston
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!