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.
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.
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.
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.
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.
It's pretty obvious that the entry point of your program should be visible.
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