Java主方法的方法签名是:
public static void main(String[] args) {
...
}
为什么这个方法必须是静态的?
Java主方法的方法签名是:
public static void main(String[] args) {
...
}
为什么这个方法必须是静态的?
当前回答
基本上,我们将这些数据成员和成员函数设置为STATIC,它们不执行任何与对象相关的任务。对于main方法,我们将其设置为STATIC,因为它与object无关,因为无论我们是否创建对象,main方法总是运行。
其他回答
让我用更简单的方式来解释这些事情:
public static void main(String args[])
除了applet,所有Java应用程序都从main()开始执行。
关键字public是一个访问修饰符,允许从类外部调用成员。
使用Static是因为它允许调用main()而不必实例化该类的特定实例。
Void表示main()不返回任何值。
基本上,我们将这些数据成员和成员函数设置为STATIC,它们不执行任何与对象相关的任务。对于main方法,我们将其设置为STATIC,因为它与object无关,因为无论我们是否创建对象,main方法总是运行。
在Java中声明为静态的任何方法都属于类本身。 同样,特定类的静态方法只能通过引用类Class_name.method_name();
因此,在访问静态方法之前不需要实例化类。
因此main()方法被声明为静态的,这样就可以在不创建该类对象的情况下访问它。
因为我们用存在main方法的类名来保存程序(或者从程序开始执行的地方开始,适用于没有main()方法()的类(高级级别))。所以通过上面提到的方法:
Class_name.method_name();
可以访问主方法。
简而言之,当程序被编译时,它会在类中搜索main()方法,其String参数如下:main(String args[])。由于在开始时它没有实例化该类的作用域,因此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.
因为静态成员不是任何特定类的一部分,而且主方法不需要创建它的Object,但仍然可以引用所有其他类。