Reputation: 886
I have been reading Thinking in Java from Bruce Eckel these days, when comes to the Access Control chapter, it says if a java file has two or more classes, except the public one, others can not be private
(that would make it inaccessible to anyone but the class) or protected
.
But I have seen a lot of popular java libraries and open source projects did have used private to decorate these kind of classes.
So is it because the book too theoretical or any reason else?
the original text (page 231, forth edition)
Note that a class can not be private (that would make it inaccessible to anyone but the class) or protected. So you have only two choices for class acess: package acces or public. If you don`t want anyone else to have access to that class, you can make all the constructors private, thereby preventing anyone but you, inside a static member of the class, form creating an object of that class.
Upvotes: 0
Views: 72
Reputation: 81074
The statement is only true for top-level (non-nested) classes. Nested classes may be private
. That's because top-level classes have visibility into private nested classes (including the private members of a nested class), and vice versa. They may also be protected
, meaning subclasses of the enclosing class, even in another package, can reference them.
Note that this isn't unique to Java files that declare more than one top-level class. private
and protected
are not allowed on any top-level class declaration.
Upvotes: 3