爲了避免無法確定該調用的構造函數而需將main函數設爲先於類的構造而執行,故將其聲明爲static


避免無法確定該調用的構造函數而需將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方法,又有誰能生成類實例呢?


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章