Java主方法的方法签名是:

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

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


当前回答

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

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

其他回答

这是一个经常被问到的问题,为什么main()在Java中是静态的。

答:我们知道在Java中,JVM从main()开始执行。当JVM执行main()时,包含main()的类不会被实例化,因此我们不能在没有引用它的对象的情况下调用非静态方法。因此,为了调用它,我们将其设置为静态的,因此类装入器将所有静态方法装入JVM上下文内存空间中,JVM可以从那里直接调用它们。

public static void main(String args[])是什么意思?

public is an access specifier meaning anyone can access/invoke it such as JVM(Java Virtual Machine. static allows main() to be called before an object of the class has been created. This is neccesary because main() is called by the JVM before any objects are made. Since it is static it can be directly invoked via the class. class demo { private int length; private static int breadth; void output(){ length=5; System.out.println(length); } static void staticOutput(){ breadth=10; System.out.println(breadth); } public static void main(String args[]){ demo d1=new demo(); d1.output(); // Note here output() function is not static so here // we need to create object staticOutput(); // Note here staticOutput() function is static so here // we needn't to create object Similar is the case with main /* Although: demo.staticOutput(); Works fine d1.staticOutput(); Works fine */ } } Similarly, we use static sometime for user defined methods so that we need not to make objects. void indicates that the main() method being declared does not return a value. String[] args specifies the only parameter in the main() method. args - a parameter which contains an array of objects of class type String.

这背后的原因很简单,因为对象不需要调用静态方法,如果它是非静态方法,java虚拟机先创建对象,然后调用main()方法,这将导致额外的内存分配问题。

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

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

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