The method signature of a Java main() method is:
public static void main(String[] args){
...
}
Is there a reason for this method to be static?
The method signature of a Java main() method is:
public static void main(String[] args){
...
}
Is there a reason for this method to be static?
Before the main method is called, no objects are instantiated. Having the static keyword means the method can be called without creating any objects first.
Basically we make those DATA MEMBERS and MEMBER FUNCTIONS as STATIC which are not performing any task related to an object. And in case of main method, we are making it as an STATIC because it is nothing to do with object, as the main method always run whether we are creating an object or not.
The
main()
method inC++
,C#
andJava
are staticBecause they can then be invoked by the runtime engine without having to instantiate any objects then the code in the body of
main()
will do the rest.Any method declared as static in Java belongs to the class itself . Again static method of a particular class can be accessed only by referring to the class like
Class_name.method_name();
So a class need not to be instantiated before accessing a static method.
So the main() method is declared as
static
so that it can be accessed without creating an object of that class.Since we save the program with the name of the class where the main method is present( or from where the program should begin its execution, applicable for classes without a
main()
method()(Advanced Level)). So by the above mentioned way:the main method can be accessed.
In brief when the program is compiled it searches for the
main()
method havingString
arguments like:main(String args[])
in the class mentioned(i.e. by the name of the program), and since at the the beginning it has no scope to instantiate that class, so the main() method is declared as static.Static methods don't require any object. It runs directly so main runs directly.
Applets, midlets, servlets and beans of various kinds are constructed and then have lifecycle methods called on them. Invoking main is all that is ever done to the main class, so there is no need for a state to be held in an object that is called multiple times. It's quite normal to pin main on another class (although not a great idea), which would get in the way of using the class to create the main object.