is there any benefit of writing public classes for

2019-05-18 11:51发布

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?

3条回答
别忘想泡老子
2楼-- · 2019-05-18 12:24

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.

查看更多
再贱就再见
3楼-- · 2019-05-18 12:43

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.

查看更多
我想做一个坏孩纸
4楼-- · 2019-05-18 12:48

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.

查看更多
登录 后发表回答