Reputation: 5213
Most programs I see have main method inside a public class, in contrast to a no-modifier class. eg:
public class Main
{
public static void main(String[] args)
{
System.out.println("Hello, World!");
}
}
rather than
class Main
{
public static void main(String[] args)
{
System.out.println("Hello, World!");
}
}
From what I read, the only reason to have the class explicitly public, is to make it visible to classes outside its' own package.
The job of main is merely to act as a plugin to your actual program API that can be easily interchanged with any other class with main with it(GUIs/CUIs change all the time, and must be designed to be disposable).
If I do not intend the class to be visible to other Java classes; and if I need it to be, I can create a new container class for a new main which is aware that it may be used by other classes, and it would be public.
Is there any reason to make container classes for main "public" by default, other than teaching people to name their classes the same way as the class within it(which is not enforced if you omit public, and causes confusion of "why does Foo.java produce Main.class?")?
Upvotes: 2
Views: 123
Reputation: 43651
I don't thing there are technical reasons for this.
Non-technical reasons I can think of are:
public
means public, no modifier means package-private. I would consider main class to be intended for public usage, so public
is a better expression of this intention.Upvotes: 0
Reputation: 691685
I think there are 3 reasons why it's usually done this way:
Upvotes: 4