Java主方法的方法签名是:
public static void main(String[] args) {
...
}
为什么这个方法必须是静态的?
Java主方法的方法签名是:
public static void main(String[] args) {
...
}
为什么这个方法必须是静态的?
当前回答
在main方法被调用之前,没有对象被实例化。使用static关键字意味着可以在不创建任何对象的情况下调用方法。
其他回答
public关键字是一个访问修饰符,它允许程序员进行控制 类成员的可见性。当类成员前面有public时,则 成员可以由声明它的类之外的代码访问。
public的反义词是private,它防止成员被定义在类外部的代码使用。
在这种情况下,main()必须声明为public,因为必须调用它 当程序启动时,由其类之外的代码执行。
关键字static允许 Main()被调用,而不必实例化类的特定实例。这是必要的,因为Java解释器在创建任何对象之前调用main()。
关键字void只是告诉编译器main()不返回值。
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语言支持实例方法作为“入口点”,那么运行时将需要在内部将其作为静态方法实现,该方法构造对象的实例,然后调用实例方法。
有了这些,我将研究选择以下三个选项中的一个的基本原理:
我们今天看到的静态void main()。 在新构造的对象上调用的实例方法void main()。 使用类型的构造函数作为入口点(例如,如果入口类被称为Program,那么执行将有效地由新的Program()组成)。
分解:
静态无效主()
调用外围类的静态构造函数。 调用静态方法main()。
void main ()
调用外围类的静态构造函数。 通过有效调用new ClassName()构造外围类的实例。 调用实例方法main()。
新ClassName ()
调用外围类的静态构造函数。 构造类的实例(然后不做任何操作,只是返回)。
理由是:
这个我倒着讲。
请记住,Java的设计目标之一是强调(尽可能要求)良好的面向对象编程实践。在这种情况下,对象的构造函数初始化对象,但不应该对对象的行为负责。因此,给出new ClassName()入口点的规范会使新Java开发人员感到困惑,因为它强制每个应用程序上的“理想”构造函数设计出现异常。
通过将main()设置为实例方法,可以解决上述问题。但是,它要求规范列出入口类的构造函数的签名以及main()方法的签名,从而增加了复杂性。
总而言之,指定静态void main()将创建复杂度最低的规范,同时遵循将行为置于方法中的原则。考虑到实现main()方法本身构造类的实例并调用实例方法是多么简单,将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.
static -当JVM调用主方法时,被调用的类不存在对象,因此它必须有静态方法来允许从类调用。