1. 程式人生 > >java初始化

java初始化

color 默認值 ava 對象 ack 二進制 con new rom

java中一切皆對象,那就從對象初始化開始說起。

示例代碼:

 1 package test;
 2 
 3 public class A extends B {
 4 
 5     int i;
 6     static int b;
 7     public D firstD = new D("A");
 8     public static C firstC = new C("A");
 9     public static C secondC;
10     {
11         System.out.println("i:"+i);//此時i未初始化,為默認值0
12 System.out.println("b:"+b); 13 System.out.println(secondC); 14 } 15 A(){ 16 17 System.out.println("here is A"); 18 i = 1; 19 b = 1; 20 } 21 22 public static void main(String[] args) { 23 // TODO 自動生成的方法存根 24 new
A(); 25 } 26 27 } 28 29 class B { 30 public static C CinB = new C("B"); 31 public D DinB = new D("B"); 32 B(){ 33 System.out.println("here is B"); 34 } 35 } 36 37 class C { 38 C(String source){ 39 System.out.println("here is C from"+source);
40 } 41 } 42 43 class D { 44 D(String source){ 45 System.out.println("here is D from"+source); 46 } 47 }

輸出:

here is C fromB
here is C fromA
here is D fromB
here is B
here is D fromA
i:0
b:0
null
here is A

結論:

1.在初始化時,首先為對象分配一塊存儲空間(默認為二進制0)

2.初始化順序:基類靜態成員->子類靜態成員->基類非靜態成員/實例初始化->基類構造器->子類非靜態成員/實例初始化->子類構造器

java初始化