I wrote the following codeclass Hello //Note the class is not public
{
public static void main(String args[]) {
System.out.println("Hello");
}
}
So, when I run it, it runs fine and prints the output "Hello".
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" Hello.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"?
And if the JVM is able to see all classes and methods as it is the "security/visibility enforcer" itself then why does the main method needs to be declared as public.
解决方案
Just for kicks, a demo that private classes can also hold main:
class Outer {
private static class Inner {
public static void main(String[] args) {
System.out.println("Hello from Inner!");
}
}
}
Compiles and runs fine from the command line:
C:\junk>javac Outer.java
C:\junk>java Outer$Inner
Hello from Inner!
C:\junk>