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?
Because the JLS, Section 12.1.4, says so:
If it's not
public
, then it won't be found; you'll getI 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
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.
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.