Java主方法的方法签名是:
public static void main(String[] args) {
...
}
为什么这个方法必须是静态的?
Java主方法的方法签名是:
public static void main(String[] args) {
...
}
为什么这个方法必须是静态的?
当前回答
因为静态成员不是任何特定类的一部分,而且主方法不需要创建它的Object,但仍然可以引用所有其他类。
其他回答
如果主方法不是静态的,则需要从程序外部创建主类的对象。你想怎么做呢?
public关键字是一个访问修饰符,它允许程序员进行控制 类成员的可见性。当类成员前面有public时,则 成员可以由声明它的类之外的代码访问。
public的反义词是private,它防止成员被定义在类外部的代码使用。
在这种情况下,main()必须声明为public,因为必须调用它 当程序启动时,由其类之外的代码执行。
关键字static允许 Main()被调用,而不必实例化类的特定实例。这是必要的,因为Java解释器在创建任何对象之前调用main()。
关键字void只是告诉编译器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.
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.
这只是一种惯例,但可能比另一种更方便。使用静态主程序,调用Java程序所需要知道的只是类的名称和位置。如果它不是静态的,您还必须知道如何实例化该类,或者要求该类具有空构造函数。