Java主方法的方法签名是:
public static void main(String[] args) {
...
}
为什么这个方法必须是静态的?
Java主方法的方法签名是:
public static void main(String[] args) {
...
}
为什么这个方法必须是静态的?
当前回答
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.
其他回答
我不知道JVM是否在对象实例化之前调用main方法…但是main()方法是静态的还有一个更有力的原因…当JVM调用类的主方法(比如Person)时。它通过"Person.main()"调用它。您可以看到,JVM通过类名调用它。这就是为什么main()方法应该是静态和公共的,以便JVM可以访问它。
希望有帮助。如果是的话,请在评论中告诉我。
如果主方法不是静态的,则需要从程序外部创建主类的对象。你想怎么做呢?
基本上,我们将这些数据成员和成员函数设置为STATIC,它们不执行任何与对象相关的任务。对于main方法,我们将其设置为STATIC,因为它与object无关,因为无论我们是否创建对象,main方法总是运行。
在Java中声明为静态的任何方法都属于类本身。 同样,特定类的静态方法只能通过引用类Class_name.method_name();
因此,在访问静态方法之前不需要实例化类。
因此main()方法被声明为静态的,这样就可以在不创建该类对象的情况下访问它。
因为我们用存在main方法的类名来保存程序(或者从程序开始执行的地方开始,适用于没有main()方法()的类(高级级别))。所以通过上面提到的方法:
Class_name.method_name();
可以访问主方法。
简而言之,当程序被编译时,它会在类中搜索main()方法,其String参数如下:main(String args[])。由于在开始时它没有实例化该类的作用域,因此main()方法被声明为静态的。
The main method of the program has the reserved word static which means it is allowed to be used in the static context. A context relates to the use of computer memory during the running of the program. When the virtual machine loads a program, it creates the static context for it, allocating computer memory to store the program and its data, etc.. A dynamic context is certain kind of allocation of memory which is made later, during the running of the program. The program would not be able to start if the main method was not allowed to run in the static context.