您的位置:首页 > 大数据 > 人工智能

为了避免无法确定该调用的构造函数而需将main函数设为先于类的构造而执行,故将其声明为static

2011-08-20 15:19 253 查看



避免无法确定该调用的构造函数而需将main函数设为先于类的构造而执行,故将其声明为static。

前几天,曾同学问我为什么Java main函数带有static,我一时也不明白,只好说是Java的main函数的格式是规定的,我也一直这样写下来,然后赶紧去查。

原谅我,我忘记这是在哪个网站/论坛找到的了,因为当时没记录,只有在聊天记录中找到了当时copy下来的我觉得可以说得过去的解释。

The
method is static because otherwise there would be ambiguity: which constructor should be called? Especially if your class looks like this:

1

2

3

4

5

public class JavaClass{

protected JavaClass(int x){}

public void main(String[] args){

}

}
Should
the JVM call new JavaClass(int)? What should it pass for x?

If
not, should the JVM instantiate JavaClass without running any constructor method? I think it shouldn’t, because that will special-case your entire class – sometimes you have an instance that hasn’t been initialized, and you have to check for it in every method
that could be called.

There
are just too many edge cases and ambiguities for it to make sense for the JVM to have to instantiate a class before the entry point is called. That’s why main is static.

个人对以上的理解就是为了避免无法确定该调用的构造函数而需将main函数设为先于类的构造而执行,故将其声明为static。

如果没法调用main方法,又有谁能生成类实例呢?

在Java中,main()方法的声明为:public static void main(String args[])。必须这么定义,这是Java的规范。
  为什么要这么定义,和JVM的运行有关系。
  当一个类中有main()方法,执行命令“java 类名”则会启动虚拟机执行该类中的main方法。
  由于JVM在运行这个Java应用程序的时候,首先会调用main方法,调用时不实例化这个类的对象,而是通过类名直接调用因此需要是限制为public static。
  对于java中的main方法,jvm有限制,不能有返回值,因此返回值类型为void。
  main方法中还有一个输入参数,类型为String[],这个也是java的规范,main()方法中必须有一个入参,类细必须String[],至于字符串数组的名字,这个是可以自己设定的,根据习惯,这个字符串数组的名字一般和sun java规范范例中mian参数名保持一致,取名为args。
  因此,main()方法定义必须是:“public static void main(String 字符串数组参数名[])”。

通俗而言,借用某笔者的话:

public, jvm对于类来说是外部调用,不用public的话没有权限去接触到main方法。static 是保证在class loading的时候就能够调用main方法了(使用class object)。如果不是static,那样就一定要生成类实例。但如果没法调用main方法,又有谁能生成类实例呢?
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐