New console project template creates a Main method like this:
class Program { static void Main(string[] args) { } }
Why is it that neither the Main
method nor the Program
class need to be public?
The Main method is the entry point of an executable program; it is where the program control starts and ends. Main is declared inside a class or struct. Main must be static and it need not be public .
We know that anyone can access/invoke a method having public access specifier. 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.
This is the access modifier of the main method. It has to be public so that java runtime can execute this method. Remember that if you make any method non-public then it's not allowed to be executed by any program, there are some access restrictions applied. So it means that the main method has to be public.
Why the main () method in Java is always static? Java main() method is always static, so that compiler can call it without the creation of an object or before the creation of an object of the class. In any Java program, the main() method is the starting point from where compiler starts program execution.
The entry point of a program is marked with the .entrypoint
IL directive. It does not matter if the method or the class is public or not, all that matters is this directive.
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