Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How come public and friendly(default) access is allowed for top level class but not

 
Chiran Mathur
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
protected or private
 
Jessica Sant
Sheriff
Posts: 4313
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
well, to be blunt and un-helpful
1- "because Sun made it that way."
But... to give a little bit more explanation:
2- Cause the JLS says so
(real helpful there huh?)
How's this one -->
3- it wouldn't make sense to make a top-level class as private -- how would you access it to run it? No other class could see it!
4- There's sorta no point to mark a top-level class as protected -- protected access gives you the same access as default (package/friendly) but you can also see it from a sub-class. But how would that work when it's a top-level class that you're referring to?
 
Jasper Vader
Ranch Hand
Posts: 284
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Jessica Sant:
protected access gives you the same access as default (package/friendly) but you can also see it from a sub-class. But how would that work when it's a top-level class that you're referring to?


if a top-level class had protected access couldn't another class from another package then extend it and thus access it?
ps- interesting poem you have there in your sig jessica!
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The problem is - in order to extend a class, the class definition must already be visible to you. (E.g. you couldn't extend a private class, period.) Before a protected class can be visible to you, you have to extend it. Which comes first? I don't really see a logical way around this problem, and moreover I don't see any real benefit to having a protected class anyway. You can always make all the methods, constructors and fields protected or private, while making the class itself public - this would prevent any outside code from doing anything significant with the class. So there's no real need for Java to allow protected classes anyway, and they'd just cause confusion.
And as Jessica said, there's no way to make use of a private top-level class - so it makes even more sense to ban this possiblity.
 
Jasper Vader
Ranch Hand
Posts: 284
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks Jim, Jessica, good words. interesting question!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic