物件初始化過程

2021-07-13 11:39:14 字數 1992 閱讀 8679

1. 這是個筆記.

helloparent.class

public class helloparent 

public helloparent()

}

hellochild.class

public class hellochild extends helloparent      

public hellochild()

public static void main(string args)

}

helloy.class

public class helloy 

}

這裡我們先看執行的結果是什麼:

parent static block

child static block

this is y

parent construct

this is y

child construct

2.我簡單說下這個過程,如果說得不對,請指出,謝謝.

這裡我們可以看到主函式main 方法hellochild.class

所以我們執行hellochild.class

當執行new hellochild()時,由於是 hellochild 繼承了helloparent 類 ,先執行父類的方法.

1.它首先去看父類裡面有沒有靜態**塊,如果有,它先去執行父類裡面靜態**塊裡面的內容

2.再去執行子類(自己這個類)裡面的靜態**塊

3.然後去看父類有沒有非靜態**塊,如果有就執行父類的非靜態**塊

4.接著執行父類的構造方法

5.緊接著它會去看子類有沒有非靜態**塊,如果有就執行子類的非靜態**塊

6.最後去執行子類的構造方法

以上是基於本例來講解的乙個物件初始化過程,如果某些方法沒有,就不會去執行.

3.一些注意事項

靜態**塊只執行一次

主函式main 方法

public static void main(string args)
這次執行的結果是

parent static block

child static block

this is y

parent construct

this is y

child construct

this is y

parent construct

this is y

child construct

你們也發現了.靜態**塊只會執行一次.

4.總結

1.如果有些**必須在專案啟動的時候就執行,需要使用靜態**塊,這種**是主動執行的;

2.需要在專案啟動的時候就初始化,在不建立物件的情況下,其他程式來呼叫的時候,需要使用靜態方法,這種**是被動執行的.

3.靜態方法在類載入的時候 就已經載入 可以用類名直接呼叫 . 比如main方法就必須是靜態的 這是程式入口

4.兩者的區別就是:靜態**塊是自動執行的;靜態方法是被呼叫的時候才執行,而且不新建物件.

歡迎指正.

物件初始化過程

class person 靜態 塊 static 構造 塊 public void setname string name public void speak public static void showcountry class newperson 當程式執行到person p new pers...

物件的初始化過程

public class persond persond string name,int age public void setname string name public void speak public static void showcountry persond p new person...

java物件初始化過程

假設有一下類 class test test int n 0 我們知道,任何物件在使用前都會被初始化,方法裡面的區域性變數必須給初始化值才能通過編譯。現在我們來討論一下初始化的過程 對於字段 變數 而言,如果是基本型別,那麼即使不給初始值,都會得到jvm預設的初始值 boolean預設是false,...