Java主方法的方法签名是:

public static void main(String[] args) {
    ...
}

为什么这个方法必须是静态的?


当前回答

我不知道JVM是否在对象实例化之前调用main方法…但是main()方法是静态的还有一个更有力的原因…当JVM调用类的主方法(比如Person)时。它通过"Person.main()"调用它。您可以看到,JVM通过类名调用它。这就是为什么main()方法应该是静态和公共的,以便JVM可以访问它。

希望有帮助。如果是的话,请在评论中告诉我。

其他回答

让我用更简单的方式来解释这些事情:

public static void main(String args[])

除了applet,所有Java应用程序都从main()开始执行。

关键字public是一个访问修饰符,允许从类外部调用成员。

使用Static是因为它允许调用main()而不必实例化该类的特定实例。

Void表示main()不返回任何值。

该方法是静态的,否则就会产生歧义:应该调用哪个构造函数?特别是如果你的类是这样的:

public class JavaClass{
  protected JavaClass(int x){}
  public void main(String[] args){
  }
}

JVM是否应该调用新的JavaClass(int)?x应该通过什么?

如果不是,JVM是否应该实例化JavaClass而不运行任何构造函数方法?我认为不应该这样,因为那样会使你的整个类出现特殊情况——有时你有一个没有初始化的实例,你必须在每个可能被调用的方法中检查它。

在调用入口点之前,JVM必须实例化一个类,这有太多的边缘情况和模糊性,因此没有意义。这就是为什么main是静态的。

我不知道为什么main总是被标记为public。

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.

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

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

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