Java主方法的方法签名是:

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

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


当前回答

最近,类似的问题也出现在了程序员网站上。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... ...

其他回答

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

public static void main(String args[])

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

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

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

Void表示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.

在main方法被调用之前,没有对象被实例化。使用static关键字意味着可以在不创建任何对象的情况下调用方法。

让我们简单地假设,静态不需要作为应用程序入口点。

一个应用程序类看起来是这样的:

class MyApplication {
    public MyApplication(){
        // Some init code here
    }
    public void main(String[] args){
        // real application code here
    }
}

构造函数代码和主方法之间的区别是必要的,因为在OO中,构造函数只应确保实例被正确初始化。初始化后,实例可以用于预期的“服务”。将完整的应用程序代码放到构造函数中会破坏这一点。

因此,这种方法将在应用程序上强制执行三个不同的契约:

必须有一个默认构造函数。否则,JVM将不知道调用哪个构造函数以及应该提供哪些参数。 必须有一个主要的方法。好吧,这并不奇怪。 类不能是抽象的。否则,JVM无法实例化它。

另一方面,静态方法只需要一个契约:

必须有一个主要的方法。

这里抽象构造函数和多重构造函数都不重要。

由于Java被设计为一种简单的语言,所以应用程序入口点被设计为使用一个简单的契约,而不是使用三个独立而脆弱的契约,这并不奇怪。

请注意:这个参数不是关于JVM或JRE内部的简单性。这个参数是关于用户的简单性。

在这里,完整的签名只能算作一份合同。

各种类型的applet、midlet、servlet和bean被构造,然后在它们上调用生命周期方法。调用main是对主类所做的全部工作,因此不需要在被多次调用的对象中保存状态。将main固定在另一个类上是很正常的(尽管这不是一个好主意),这将妨碍使用类创建main对象。