Java主方法的方法签名是:
public static void main(String[] args) {
...
}
为什么这个方法必须是静态的?
Java主方法的方法签名是:
public static void main(String[] args) {
...
}
为什么这个方法必须是静态的?
当前回答
让我用更简单的方式来解释这些事情:
public static void main(String args[])
除了applet,所有Java应用程序都从main()开始执行。
关键字public是一个访问修饰符,允许从类外部调用成员。
使用Static是因为它允许调用main()而不必实例化该类的特定实例。
Void表示main()不返回任何值。
其他回答
我不知道JVM是否在对象实例化之前调用main方法…但是main()方法是静态的还有一个更有力的原因…当JVM调用类的主方法(比如Person)时。它通过"Person.main()"调用它。您可以看到,JVM通过类名调用它。这就是为什么main()方法应该是静态和公共的,以便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命令运行Java虚拟机(JVM)时,
java ClassName argument1 argument2 ...
当您执行您的应用程序时,您指定它的类名作为java命令的参数,如上所述
JVM尝试调用您指定的类的主方法
-在这一点上,类的对象还没有被创建。 将main声明为静态允许JVM在不创建的情况下调用main 类的实例。
让我们回到命令
ClassName是JVM的命令行参数,它告诉JVM要执行哪个类。在ClassName之后,您还可以指定一个字符串列表(由空格分隔)作为JVM将传递给应用程序的命令行参数。-这些参数可以用来指定运行应用程序的选项(例如文件名)-这就是为什么在main中有一个名为String[] args的参数
参考资料:Java™如何编程(早期对象),第十版
这是一个经常被问到的问题,为什么main()在Java中是静态的。
答:我们知道在Java中,JVM从main()开始执行。当JVM执行main()时,包含main()的类不会被实例化,因此我们不能在没有引用它的对象的情况下调用非静态方法。因此,为了调用它,我们将其设置为静态的,因此类装入器将所有静态方法装入JVM上下文内存空间中,JVM可以从那里直接调用它们。
该方法是静态的,否则就会产生歧义:应该调用哪个构造函数?特别是如果你的类是这样的:
public class JavaClass{
protected JavaClass(int x){}
public void main(String[] args){
}
}
JVM是否应该调用新的JavaClass(int)?x应该通过什么?
如果不是,JVM是否应该实例化JavaClass而不运行任何构造函数方法?我认为不应该这样,因为那样会使你的整个类出现特殊情况——有时你有一个没有初始化的实例,你必须在每个可能被调用的方法中检查它。
在调用入口点之前,JVM必须实例化一个类,这有太多的边缘情况和模糊性,因此没有意义。这就是为什么main是静态的。
我不知道为什么main总是被标记为public。