aspose file tools*
The moose likes Beginning Java and the fly likes Declaring members of a non-public class as public Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Declaring members of a non-public class as public" Watch "Declaring members of a non-public class as public" New topic
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: 40043
    
  28
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: 24187
    
  34

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: 40043
    
  28
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Declaring members of a non-public class as public