java對象初始化的順序

Java代碼  

  1. public class Son extends Father {  

  2.   

  3.     String value = null;//2  

  4.   

  5.     public Son() {  

  6.         super();  //1  

  7.         System.out.println("Son:  " + value);//3  

  8.     }  

  9.   

  10.     public static void main(final String[] args) {  

  11.         new Son();  

  12.     }  

  13. }  

  14.   

  15.   

  16. class Father {  

  17.   

  18.     public Father() {  

  19.         if (this instanceof Son) {  

  20.             Son lower = (Son) this;  

  21.             lower.value = "test";  

  22.         }  

  23.     }  

  24. }  

  25.   

  26.   

  27. class Father {  

  28.   

  29.     public Father() {  

  30.         if (this instanceof Son) {  

  31.             Son lower = (Son) this;  

  32.             lower.value = "test";  

  33.         }  

  34.     }  

  35. }  


下載

這個的結果是 null 
步驟1  設置爲test 
步驟2  設置爲null 
步驟3 打印出來null 

如果 不是   String value = null ; 只是   String value; 下載

步驟1  設置爲test 
步驟2  不做任何事情,因爲已經有值了,不用設置爲默認的null值了 
步驟3 打印出來null
 

所以  一個字段不設置值 和 設置爲null  是有區別的。 


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