Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why a class containg a main method doesn't need to be public in Java? [duplicate]

Tags:

java

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.

like image 797
Zaid Khan Avatar asked Sep 04 '13 15:09

Zaid Khan


People also ask

What happens if main method is not public in Java?

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.

Can we run main method without public?

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.

Is it necessary to make main class public?

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.

Should a main () method be compulsorily declared in all Java classes?

main is usually declared as static method and hence Java doesn't need an object to call the main method.


1 Answers

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>

like image 179
Ted Hopp Avatar answered Nov 14 '22 21:11

Ted Hopp