Java主方法的方法签名是:
public static void main(String[] args) {
...
}
为什么这个方法必须是静态的?
Java主方法的方法签名是:
public static void main(String[] args) {
...
}
为什么这个方法必须是静态的?
当前回答
The main method of the program has the reserved word static which means it is allowed to be used in the static context. A context relates to the use of computer memory during the running of the program. When the virtual machine loads a program, it creates the static context for it, allocating computer memory to store the program and its data, etc.. A dynamic context is certain kind of allocation of memory which is made later, during the running of the program. The program would not be able to start if the main method was not allowed to run in the static context.
其他回答
The main method of the program has the reserved word static which means it is allowed to be used in the static context. A context relates to the use of computer memory during the running of the program. When the virtual machine loads a program, it creates the static context for it, allocating computer memory to store the program and its data, etc.. A dynamic context is certain kind of allocation of memory which is made later, during the running of the program. The program would not be able to start if the main method was not allowed to run in the static context.
因为静态成员不是任何特定类的一部分,而且主方法不需要创建它的Object,但仍然可以引用所有其他类。
在main方法被调用之前,没有对象被实例化。使用static关键字意味着可以在不创建任何对象的情况下调用方法。
这只是一种惯例。JVM当然可以处理非静态的主方法,如果这是惯例的话。毕竟,您可以在类上定义静态初始化器,并在到达main()方法之前实例化无数对象。
最近,类似的问题也出现在了程序员网站上。SE
为什么在Java和c#中使用静态主方法,而不是构造函数? 从主要或次要来源中寻找一个明确的答案,为什么(特别是)Java和c#决定将静态方法作为它们的入口点-而不是通过应用程序类的实例表示应用程序实例,入口点是一个适当的构造函数?
公认的答案是,
In Java, the reason of public static void main(String[] args) is that Gosling wanted the code written by someone experienced in C (not in Java) to be executed by someone used to running PostScript on NeWS For C#, the reasoning is transitively similar so to speak. Language designers kept the program entry point syntax familiar for programmers coming from Java. As C# architect Anders Hejlsberg puts it, ...our approach with C# has simply been to offer an alternative... to Java programmers... ...