Java主方法的方法签名是:

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

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


当前回答

public静态void关键字意味着Java虚拟机(JVM)解释器可以调用程序的主方法来启动程序(public),而无需创建类的实例(static),并且程序结束时不会将数据返回给Java VM解释器(void)。

来源: 要领,第1部分,第2课:构建应用程序

其他回答

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

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

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

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

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

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

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

必须有一个主要的方法。

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

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

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

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

否则,它将需要一个对象的实例来执行。但是它必须从头开始调用,而不是首先构造对象,因为它通常是main()函数(bootstrap)的任务,解析参数并构造对象,通常是通过使用这些参数/程序参数。

static -当JVM调用主方法时,被调用的类不存在对象,因此它必须有静态方法来允许从类调用。

如果不是,如果有多个构造函数,应该使用哪个构造函数?

在Java语言规范中有更多关于Java程序初始化和执行的信息。

The static key word in the main method is used because there isn't any instantiation that take place in the main method. But object is constructed rather than invocation as a result we use the static key word in the main method. In jvm context memory is created when class loads into it.And all static members are present in that memory. if we make the main static now it will be in memory and can be accessible to jvm (class.main(..)) so we can call the main method with out need of even need for heap been created.