Why main method is marked as public?

2019-01-15 03:21发布

I have a question that why main method is marked as public?

According to an answer on stackoverflow, It is declared as static

"The method is static because otherwise there would be ambiguity: which constructor should be called?"

But, can anyone can explain why it is declared public always?

标签: java main public
9条回答
戒情不戒烟
2楼-- · 2019-01-15 04:04

Yes the standards say so that main method should be public in Java. But it's not only for Java. However even for C#, main must be public.

So just think about it in real world scenarios.

E.g. you want to enter your room, but you should enter your home main door first (given room is inside the house...and no other means to enter the house)

Main door is the only publicly available access point.

查看更多
Luminary・发光体
3楼-- · 2019-01-15 04:11

Public - main method is called by JVM to run the method which is outside the scope of project therefore the access specifier has to be public to permit call from anywhere outside the application.

From coderanch

查看更多
走好不送
4楼-- · 2019-01-15 04:11

When the code is executed, a JVM will be created and that will act as a container for the code we are trying to execute. Declaring this method as public allows the JVM to start the code execution. If method is private, JVM wont be able to call it. There are ways to call a private method as well (eg by using Reflection), but that is not a standard way to do things.

查看更多
男人必须洒脱
5楼-- · 2019-01-15 04:17

The initialization software that starts your program must be able to see main so that it can call it.

查看更多
ゆ 、 Hurt°
6楼-- · 2019-01-15 04:21

Because that is what is known as the "entry point" and if it is private, your program will not be able to run.

查看更多
SAY GOODBYE
7楼-- · 2019-01-15 04:22

Because the main method should be accessed by JVM without any restrictions from any where. I think you can find more info here: Why main method is public

查看更多
登录 后发表回答