Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why is it mandatory to declare main method public...Why it is not possible for JVM to execute private main method

Tags:

java

Generally I find in various books that main method should be public because it should be visible to classloader. But JVM executes(or provides special handling of) various private methods say readObject/writeObject method in ObjectOutputStream.

like image 234
Ashish Avatar asked Jun 25 '11 10:06

Ashish


People also ask

Why is it necessary to declare main method as public?

The main method is public in Java because it has to be invoked by the JVM. So, if main() is not public in Java, the JVM won't call it. That's all about why the main method is declared public and static in Java.

Why we can't declare the main method of our class as private?

Yes, we can declare the main method as private in Java. It compiles successfully without any errors but at the runtime, it says that the main method is not public.

Why main method is not private in Java?

The JVM does not have any special handling to call private methods from outside a class. The methods you named are all public. The only way you can bypass the visibility model is to use reflection, but this is wanted because it's purpose is to have deeper insight to objects.

What will happen if we declare main method as private in Java?

Declaring the main method private or, protected It searches for the main method which is public, static, with return type void, and a String array as an argument. If such a method is not found, a run time error is generated.


1 Answers

It's pretty obvious that the entry point of your program should be visible.

like image 161
Giann Avatar answered Nov 14 '22 21:11

Giann