Java主方法的方法签名是:
public static void main(String[] args) {
...
}
为什么这个方法必须是静态的?
Java主方法的方法签名是:
public static void main(String[] args) {
...
}
为什么这个方法必须是静态的?
当前回答
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.
其他回答
由于程序从main()和开始执行,java是纯面向对象的程序,其中对象在main()中声明,这意味着main()在对象创建之前被调用,因此如果main()是非静态的,那么就需要一个对象,因为静态意味着不需要对象..........
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.
各种类型的applet、midlet、servlet和bean被构造,然后在它们上调用生命周期方法。调用main是对主类所做的全部工作,因此不需要在被多次调用的对象中保存状态。将main固定在另一个类上是很正常的(尽管这不是一个好主意),这将妨碍使用类创建main对象。
最近,类似的问题也出现在了程序员网站上。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... ...
主方法总是需要是静态的,因为在运行时JVM不会创建任何对象来调用主方法,正如我们所知,在java中静态方法是唯一可以使用类名调用的方法,所以主方法总是需要是静态的。
更多信息请访问这个视频:https://www.youtube.com/watch?v=Z7rPNwg-bfk&feature=youtu.be