We can write a java program with one non-public class containing a main method -- it'll compile and run just fine. Why do people make the main class public?
Is there any benefit?
There is no benefit of making the class public for the sake of it having a main method.
That being said, there isn't really much of a reason not to either. Chances are the main class is either going to be very short with few, if any, substantial methods in it, or it's going to be baked into one of the core classes like
class Server {
public static void main(String[] args) {
Server s = new Server();
s.start();
}
// rest of Server class here
}
And typically those core classes are something you'd want to be public.
But this isn't about the benefits of having classes be public. This is about the benefits of having a class be public because it has the main method and there are no direct benefits as a result of that.
Simply because clients will have access to create objects of your class based on the accessibility you specify for your class. If you look at Java source libraries you will see lot of private (inner classes) classes too. Depends whom do you want to allow access to create objects of your class.
Benefit you will have only when classes you are using in main method doesn't belong to same package.Public class will have visibility across all the packages.
来源:https://stackoverflow.com/questions/8949801/is-there-any-benefit-of-writing-public-classes-for-the-main-method