| Author |
Declaring members of a non-public class as public
|
Suresh S Nayar
Greenhorn
Joined: Apr 25, 2009
Posts: 9
|
|
I seen code in books where there are members specified as public (and not just default access) in non-public classes. What use could this specification of members as public be in non-public classes be?
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32712
|
|
Unless they are also called static and final, they are indications to avoid those books.
Only "constants" should have public access; they are usually declared public static final. Every other field should have private access.
|
 |
Suresh S Nayar
Greenhorn
Joined: Apr 25, 2009
Posts: 9
|
|
Hey Campbell,
thanks for the reply.
But i don't see the point of Public Constants in non-public classes. If a class is not going to be public, the class won't be accessible, and thus, neither will its public members, right?
And i meant, i have seen member methods declared as public in non-public classes.
|
 |
Ernest Friedman-Hill
author and iconoclast
Marshal
Joined: Jul 08, 2003
Posts: 24061
|
|
Suresh S Nayar wrote:
And i meant, i have seen member methods declared as public in non-public classes.
Well, methods that override public methods in other classes, or that implement interface methods, must be public, even if the class is not. There are many non-public classes that implement interfaces and thus have public methods.
|
[Jess in Action][AskingGoodQuestions]
|
 |
Suresh S Nayar
Greenhorn
Joined: Apr 25, 2009
Posts: 9
|
|
Thanks Ernest,
it didn't really strike me earlier that this (overriding public methods from superclasses or implementing an Interface's methods) could be the reason that some members will HAVE to be declared as public, even if a class is not public, effectively restricting the availability of its members to the package's classes and that class's subclasses. Now i am clearer.
cheers
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32712
|
|
Restricted to the package and subclasses is protected access.
It is usual for (most) methods to be declared public; they constitute the "public interface" of the class, and ought to be accessible from any code.
|
 |
 |
|
|
subject: Declaring members of a non-public class as public
|
|
|