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:23

Because the JLS, Section 12.1.4, says so:

The method main must be declared public, static, and void. It must specify a formal parameter (§8.4.1) whose declared type is array of String.

If it's not public, then it won't be found; you'll get

Error: Main method not found in class Main, please define the main method as:
   public static void main(String[] args)
查看更多
姐就是有狂的资本
3楼-- · 2019-01-15 04:23

I believe, the rational behind enforcing main as public is more to do with the language specification – rather than whether something could be achieved or not.

Refer: http://docs.oracle.com/javase/specs/jls/se7/html/jls-12.html#jls-12.1.4

The method main must be declared public, static, and void. It must specify a formal parameter (§8.4.1) whose declared type is array of String. Therefore, either of the following declarations is acceptable:

Java uses JNI launch java application will never have any issue in calling a private main – but this is more like jail-brake (like another jail-brake, where reflection API let you access private method) and definitely not in spirit of java specification.


If I remember till JDK 1.3 – it was not mandatory from developer’s perspective. i.e. even a private main was being accepted by JRE. Though, it was not inline with JLS 1.3.

I tried searching JLS 1.3 for a reference, but could not get a link. But I found that it was reported as a bug by developers across world:

Please refer: http://bugs.java.com/bugdatabase/view_bug.do?bug_id=4155575

So, a fix was made in subsequent version to enforce rule stated by JLS.

Now, the point is why JLS writer enforced this rule at first place – I really have no idea. The only thing I can think of is that – to keep it “obvious” and non-confusing for developers.

查看更多
唯我独甜
4楼-- · 2019-01-15 04:23

In Java a function or variable in class in unaccessible untill an Object is created from the class, but the 'main' function is supposed to run at startup(without Object initiation) by JVM. So the 'main' is declared public as well as static so that it can be accessed outside class & without even an Object is created.

查看更多
登录 后发表回答