Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't the class containing main have to be public?

Tags:

java

I declared the following class

class A { //not public
  public static void main(String args[]) {
     System.out.println("done");
 }

When I compile and run it, it runs fine and prints the output "done". Same behavior even when I declare it as being in a "package a;"

However, if JVM spec mandates that main method should be public since "it can't see main otherwise", shouldn't it apply to the class as well? If the JVM "can't see" A.main() when it is not declared public, how is it able to see the class A itself.

Is there any explanation for this other than "because the specification says so"?

like image 674
Jagat Avatar asked Oct 09 '22 11:10

Jagat


1 Answers

The JVM has access to every class in the application all the time because one of its responsibilities is enforcing visibility rules. Therefore, one can draw the conclusion that it can ignore visibility rules if need be (e.g. when the user starts the application, the JVM has to find the entry point, which is main()).

In other words, the JVM is not a class accessing this function, so visibility doesn't apply. It is basically the overseer, managing the application from execution to termination.

For reference, see Execution.

like image 138
Evan Mulawski Avatar answered Oct 12 '22 12:10

Evan Mulawski