Reputation: 19037
Let's look at the method signature of main() in C, C++ and Java without paying much attention to it.
C and C++ take the syntax of the main() function something like the one shown below.
int main(void)
{
//Elegant code goes here.
return(0);
}
or it can simply be declared void as shown below.
void main(void)
{
//Elegant code goes here.
}
The main() function in C and C++ can optionally takes two command-line arguments, if needed.
The signature of the main() method in Java however, something like this.
public static void main(String []args)
{
//Elegant Java code goes here.
}
Java requires the main() method to be static simply because it was clearly mentioned that it is the first method to be invoked when no objects were created hence, it must be static. The same thing is also applicable to C and C++. There also the main() function is the first function to be invoked still they don't require the main() function to be static. Why? Why did the Java designers take somewhat different view to implement the main() method in Java?
Upvotes: 3
Views: 1580
Reputation: 41
In java, entire program is encapsulated within a single class. and that class name is usually the name of the program. Static member function of the class has the ability to be called without using any of the object and only one copy of the static member function is shared by all the object. Since main function is single for all the object of your java program and we are not using any object for calling the main function. For this reason main is declared static,
Upvotes: 4
Reputation: 8304
C has no objects and all methods are static; in C++ one has to declare methods as virtual for them to be not static.
Upvotes: 6
Reputation: 6555
If main()
is not declared as static, one would have to instantiate the class first to be able to call the method. But to be able to instantiate, one would need to have a running program. This is a catch 22, so the only way to launch the method is having it static.
Upvotes: 1
Reputation: 54924
Because main
is run without the object being instantiated. Therefore is static method.
Upvotes: 2