Click here to Skip to main content
15,912,897 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Why to write Public static void main(), if i don't write static what will happen??
Posted

Static methods have no instances. They are called with the type name, not an instance identifier. They are slightly faster than instance methods because of this. Static methods can be public or private. They cannot use the this instance expression.
 
Share this answer
 
It will throw an error, because, static main is the entry point for a program.
As static functions in a class are called direct with the class name, like for example

class Program
{
static void main(){}

void main2();
}

Main function will be called as Program.Main();

And main2 function will require an object to be made of program class and then it will called. This function will have a separate reference for all the objects, where as static functions are single and common for the complete class for all objects.
That is why it is require to have static function main, which is internally called by the compiler by the class name.
 
Share this answer
 
When a class member is declared as static, it can be accessed before any object of that class is created and without reference to any object. Both methods and variable can be declared as static. The best example to understand is our main() which is declared static. Its is static because it must be called before any object exist.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900