Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

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

 
Barry Burd
Author
Ranch Hand
Posts: 118
5
Android Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Stephan van Hulst
Bartender
Pie
Posts: 5790
61
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 48917
58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 5790
61
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you don't state public, private, or protected then it will be public automatically anyway.
 
Stephan van Hulst
Bartender
Pie
Posts: 5790
61
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic