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.
其他回答
在Java中声明为静态的任何方法都属于类本身。 同样,特定类的静态方法只能通过引用类Class_name.method_name();
因此,在访问静态方法之前不需要实例化类。
因此main()方法被声明为静态的,这样就可以在不创建该类对象的情况下访问它。
因为我们用存在main方法的类名来保存程序(或者从程序开始执行的地方开始,适用于没有main()方法()的类(高级级别))。所以通过上面提到的方法:
Class_name.method_name();
可以访问主方法。
简而言之,当程序被编译时,它会在类中搜索main()方法,其String参数如下:main(String args[])。由于在开始时它没有实例化该类的作用域,因此main()方法被声明为静态的。
这只是一个惯例,我们可以在这里看到:
方法必须声明为public和static,它不能返回任何值 值,并且它必须接受String数组作为参数。默认情况下, 第一个非选项参数是要调用的类的名称。 应该使用完全限定的类名。如果-jar选项为 指定后,第一个非选项参数是JAR存档的名称 类包含应用程序的类和资源文件 由Main-Class manifest头指示的启动类。
http://docs.oracle.com/javase/1.4.2/docs/tooldocs/windows/java.html#description
这只是一种惯例。JVM当然可以处理非静态的主方法,如果这是惯例的话。毕竟,您可以在类上定义静态初始化器,并在到达main()方法之前实例化无数对象。
这只是一种惯例,但可能比另一种更方便。使用静态主程序,调用Java程序所需要知道的只是类的名称和位置。如果它不是静态的,您还必须知道如何实例化该类,或者要求该类具有空构造函数。
Main()是静态的,因为;在应用程序生命周期的这一点上,应用程序堆栈本质上是过程化的,因为还没有实例化对象。
这是一个干净的石板。您的应用程序此时正在运行,即使没有声明任何对象(请记住,有过程性和OO编码模式)。作为开发人员,通过创建对象的实例并依赖于在其中编译的代码,将应用程序转换为面向对象的解决方案。
面向对象的优点有几百万个显而易见的理由。然而,大多数VB开发人员在代码中经常使用“goto”这样的关键字的日子已经一去不复返了。“goto”是VB中的一个过程命令,它被OO对应的方法调用所取代。
您还可以将静态入口点(main)视为纯粹的自由。如果Java足够不同,可以实例化一个对象,并在运行时只向你呈现该实例,那么你就别无选择,只能编写一个过程化应用程序。对于Java来说,这听起来可能难以想象,但可能有许多场景都需要过程化方法。
这可能是一个非常晦涩的回答。记住,“类”只是一个相互关联的代码的集合。“实例”是这个类的一个孤立的、活生生的、自主的代。