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.

其他回答

任何应用程序的真正入口点都是静态方法。如果Java语言支持实例方法作为“入口点”,那么运行时将需要在内部将其作为静态方法实现,该方法构造对象的实例,然后调用实例方法。

有了这些,我将研究选择以下三个选项中的一个的基本原理:

我们今天看到的静态void main()。 在新构造的对象上调用的实例方法void main()。 使用类型的构造函数作为入口点(例如,如果入口类被称为Program,那么执行将有效地由新的Program()组成)。

分解:

静态无效主()

调用外围类的静态构造函数。 调用静态方法main()。

void main ()

调用外围类的静态构造函数。 通过有效调用new ClassName()构造外围类的实例。 调用实例方法main()。

新ClassName ()

调用外围类的静态构造函数。 构造类的实例(然后不做任何操作,只是返回)。

理由是:

这个我倒着讲。

请记住,Java的设计目标之一是强调(尽可能要求)良好的面向对象编程实践。在这种情况下,对象的构造函数初始化对象,但不应该对对象的行为负责。因此,给出new ClassName()入口点的规范会使新Java开发人员感到困惑,因为它强制每个应用程序上的“理想”构造函数设计出现异常。

通过将main()设置为实例方法,可以解决上述问题。但是,它要求规范列出入口类的构造函数的签名以及main()方法的签名,从而增加了复杂性。

总而言之,指定静态void main()将创建复杂度最低的规范,同时遵循将行为置于方法中的原则。考虑到实现main()方法本身构造类的实例并调用实例方法是多么简单,将main()指定为实例方法并没有真正的优势。

c++、c#和Java中的主要方法是静态的。

这是因为它们可以被运行时引擎调用,而无需实例化任何对象,然后main主体中的代码将完成其余的工作。

基本上,我们将这些数据成员和成员函数设置为STATIC,它们不执行任何与对象相关的任务。对于main方法,我们将其设置为STATIC,因为它与object无关,因为无论我们是否创建对象,main方法总是运行。

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.

主方法总是需要是静态的,因为在运行时JVM不会创建任何对象来调用主方法,正如我们所知,在java中静态方法是唯一可以使用类名调用的方法,所以主方法总是需要是静态的。

更多信息请访问这个视频:https://www.youtube.com/watch?v=Z7rPNwg-bfk&feature=youtu.be