aspose file tools*
The moose likes Beginning Java and the fly likes Why the Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Why the "public" in "public class Hello"?" Watch "Why the "public" in "public class Hello"?" New topic
Author

Why the "public" in "public class Hello"?

Barry Burd
Author
Ranch Hand

Joined: Jun 18, 2003
Posts: 118
    
    5

Java programmers tend to declare a main class to be public. I think I recall seeing a situation several months ago where "public" was necessary for a class that included a main method, but I can't remember the situation. I thought it was in an Ant build(?) Anyway, is there a good reason for doing

public class Hello

instead of

class Hello

when the purpose of the Hello class is only to contain a main method?


Java For Dummies, 6th Edition, Java Programming for Android Developers For Dummies
Stephan van Hulst
Bartender

Joined: Sep 20, 2010
Posts: 3367
    
    9
As far as I know, there are no good reasons, other than maybe for some reflective purposes? I'm not sure, I never really use reflection that much.

The reason why the main class is public is because it's simply a habit for most people. As a matter of fact, many programmers have the bad habit of declaring too much public anyway.

I changed the template for a new class in my NetBeans to read final instead of public. Much better! I also added an empty private constructor. Implicit constructors have always been a bad idea in my book.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 36468
    
  16
Agree: often force of habit. But if you have the main method in a class inside a package, can you invoke it if the class has package-private access?
Stephan van Hulst
Bartender

Joined: Sep 20, 2010
Posts: 3367
    
    9
Not programmatically from another package of course, but the JVM has no problems invoking it. It just requires the main method itself to be public.
Mike Rybak
Greenhorn

Joined: Oct 08, 2011
Posts: 2
If you don't state public, private, or protected then it will be public automatically anyway.
Stephan van Hulst
Bartender

Joined: Sep 20, 2010
Posts: 3367
    
    9
No, it will be package private. This goes for the class as well as any method, including the main method.

The only things which are implicitly public are interface members and the default constructor.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Why the "public" in "public class Hello"?
 
Similar Threads
polymorph question
Quick Question
Which method gets called ?
Why this snippet does not run?
help in solving recursive problems??