is there any benefit of writing public classes for the main method?

断了今生、忘了曾经 提交于 2019-12-06 04:23:44

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!