Java主方法的方法签名是:

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

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


当前回答

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

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

其他回答

这只是一种惯例,但可能比另一种更方便。使用静态主程序,调用Java程序所需要知道的只是类的名称和位置。如果它不是静态的,您还必须知道如何实例化该类,或者要求该类具有空构造函数。

Static表示该方法是类方法。并且调用时不需要任何类的对象。

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

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

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

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.