I wrote the following code
class 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.
The main method in Java is public so that it's visible to every other class, even which are not part of its package. if it's not public JVM classes might not able to access it.
You can define the main method in your program without private, protected or, default (none) modifier, the program gets compiled without compilation errors. But, at the time of execution JVM does not consider this as the entry point of the program.
JVM can call the static methods easily without creating an instance of the class by using the class name only. As discussed above, the main() method should be public, static, and have a return type void. If we do not define it as public and static or return something from the method, it will definitely throw an error.
main is usually declared as static method and hence Java doesn't need an object to call the main method.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With