Dmytro
Dmytro

Reputation: 5213

Is there a real reason to have Java main inside a public class?

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

Answers (2)

lexicore
lexicore

Reputation: 43651

I don't thing there are technical reasons for this.

Non-technical reasons I can think of are:

  • Convention. How many people will be surprized to see non-public main class? Any profit from that surprize?
  • Expression of intention. 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

JB Nizet
JB Nizet

Reputation: 691685

I think there are 3 reasons why it's usually done this way:

  1. It feels weird to have a public static method in a class that is not public
  2. main classes are rarely exposed in a public API library, so it doesn't really matter. And IDEs generally generate public classes by default.
  3. The bootstrapping code of the VM that must call the main method is seen as code external to the package, and it thus feels right to make the class public to make it accessible to this logically external code.

Upvotes: 4

Related Questions