java对象的初始化顺序_JAVA 对象的初始化顺序
1. 這是個筆記.####
HelloParent.class
public class HelloParent {
helloY y = new helloY();
static {
System.out.println("parent static block");
}
public HelloParent() {
System.out.println("parent construct");
}
}
HelloChild.class
public class HelloChild extends HelloParent {
helloY y = new helloY();
static {
System.out.println("child static block");
}
public HelloChild() {
System.out.println("child construct");
}
public static void main(String[] args) {
new HelloChild ();
}
}
helloY.class
public class helloY {
helloY() {
System.out.println("this is Y");
}
}
這里我們先看運行的結果是什么:
parent static block
child static block
this is Y
parent construct
this is Y
child construct
2.我簡單說下這個過程,如果說得不對,請指出,謝謝.####
這里我們可以看到主函數 main 方法 在 HelloChild.class
所以我們運行 HelloChild.class
當執(zhí)行new HelloChild()時,由于是 HelloChild 繼承了HelloParent 類 ,先執(zhí)行父類的方法.
1.它首先去看父類里面有沒有靜態(tài)代碼塊,如果有,它先去執(zhí)行父類里面靜態(tài)代碼塊里面的內容#####
2.再去執(zhí)行子類(自己這個類)里面的靜態(tài)代碼塊#####
3.然后去看父類有沒有非靜態(tài)代碼塊,如果有就執(zhí)行父類的非靜態(tài)代碼塊#####
4.接著執(zhí)行父類的構造方法#####
5.緊接著它會去看子類有沒有非靜態(tài)代碼塊,如果有就執(zhí)行子類的非靜態(tài)代碼塊#####
6.最后去執(zhí)行子類的構造方法#####
以上是基于本例來講解的一個對象初始化過程,如果某些方法沒有,就不會去執(zhí)行.
3.一些注意事項####
靜態(tài)代碼塊只執(zhí)行一次
主函數 main 方法
public static void main(String[] args) {
new HelloChild ();
new HelloChild ();
}
這次運行的結果是
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
你們也發(fā)現了.靜態(tài)代碼塊只會執(zhí)行一次.
4.總結####
1.如果有些代碼必須在項目啟動的時候就執(zhí)行,需要使用靜態(tài)代碼塊,這種代碼是主動執(zhí)行的;#####
2.需要在項目啟動的時候就初始化,在不創(chuàng)建對象的情況下,其他程序來調用的時候,需要使用靜態(tài)方法,這種代碼是被動執(zhí)行的.
3.靜態(tài)方法在類加載的時候 就已經加載 可以用類名直接調用 . 比如main方法就必須是靜態(tài)的 這是程序入口#####
4.兩者的區(qū)別就是:靜態(tài)代碼塊是自動執(zhí)行的;靜態(tài)方法是被調用的時候才執(zhí)行,而且不新建對象.#####
歡迎指正.
總結
以上是生活随笔為你收集整理的java对象的初始化顺序_JAVA 对象的初始化顺序的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java怎么防止表单重复提交_如何防止表
- 下一篇: php获取excel表格内容,利用PHP