I have a question that why main method is marked as public?
According to an answer on stackoverflow, It is declared as static
"The method is static because otherwise there would be ambiguity: which constructor should be called?"
But, can anyone can explain why it is declared public always?
Yes the standards say so that
main
method should bepublic
in Java. But it's not only for Java. However even for C#,main
must bepublic
.So just think about it in real world scenarios.
E.g. you want to enter your room, but you should enter your home main door first (given room is inside the house...and no other means to enter the house)
Main door is the only publicly available access point.
Public
- main method is called by JVM to run the method which is outside the scope of project therefore the access specifier has to be public to permit call from anywhere outside the application.From coderanch
When the code is executed, a JVM will be created and that will act as a container for the code we are trying to execute. Declaring this method as public allows the JVM to start the code execution. If method is private, JVM wont be able to call it. There are ways to call a private method as well (eg by using Reflection), but that is not a standard way to do things.
The initialization software that starts your program must be able to see
main
so that it can call it.Because that is what is known as the "entry point" and if it is private, your program will not be able to run.
Because the main method should be accessed by JVM without any restrictions from any where. I think you can find more info here: Why main method is public