Why is the Java main method static?

2018-12-31 04:56发布

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?

标签: java static main
30条回答
刘海飞了
2楼-- · 2018-12-31 05:21

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.

查看更多
十年一品温如言
3楼-- · 2018-12-31 05:23

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.

查看更多
时光乱了年华
4楼-- · 2018-12-31 05:24

The main() method in C++, C# and Java are static
Because 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.

查看更多
余欢
5楼-- · 2018-12-31 05:24

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:

Class_name.method_name();

the main method can be accessed.

In brief when the program is compiled it searches for the main() method having String 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.

查看更多
查无此人
6楼-- · 2018-12-31 05:25

Static methods don't require any object. It runs directly so main runs directly.

查看更多
骚的不知所云
7楼-- · 2018-12-31 05:26

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.

查看更多
登录 后发表回答