File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Why the "public" in "public class Hello"?" Watch "Why the "public" in "public class Hello"?" New topic

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

Barry Burd
Ranch Hand

Joined: Jun 18, 2003
Posts: 118

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

Joined: Sep 20, 2010
Posts: 4192

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.

The mind is a strange and wonderful thing. I'm not sure that it will ever be able to figure itself out, everything else, maybe. From the atom to the universe, everything, except itself.
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 45255
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

Joined: Sep 20, 2010
Posts: 4192

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

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

Joined: Sep 20, 2010
Posts: 4192

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:
subject: Why the "public" in "public class Hello"?
It's not a secret anymore!