4.5:成员初始化另几个要点
当new一个新的类时,总是先初始化static方法的成员,同时此类成员也仅仅初始化一次,然后再初始化别的成员。
eg:
1 class Bowl { 2 Bowl(int marker) { 3 System.out.println("Bowl(" + marker + ")"); 4 } 5 void f(int marker) { 6 System.out.println("f(" + marker + ")"); 7 } 8 } 9 class Table { 10 static Bowl b1 = new Bowl(1); 11 Table() { 12 System.out.println("Table()"); 13 b2.f(1); 14 } 15 void f2(int marker) { 16 System.out.println("f2(" + marker + ")"); 17 } 18 static Bowl b2 = new Bowl(2); 19 } 20 class Cupboard { 21 Bowl b3 = new Bowl(3); 22 static Bowl b4 = new Bowl(4); 23 Cupboard() { 24 System.out.println("Cupboard()"); 25 b4.f(2); 26 } 27 void f3(int marker) { 28 System.out.println("f3(" + marker + ")"); 29 } 30 static Bowl b5 = new Bowl(5); 31 } 32 public class mail { 33 public static void main(String[] args) { 34 System.out.println( 35 "Creating new Cupboard() in main"); 36 new Cupboard(); 37 System.out.println( 38 "Creating new Cupboard() in main"); 39 new Cupboard(); 40 t2.f2(1); 41 t3.f3(1); 42 } 43 static Table t2 = new Table(); 44 static Cupboard t3 = new Cupboard(); 45 } ///:~
显示结果为:
Bowl(1)
Bowl(2)
Table()
f(1)
Bowl(4)
Bowl(5)
Bowl(3)
Cupboard()
f(2)
Creating new Cupboard() in main
Bowl(3)
Cupboard()
f(2)
Creating new Cupboard() in main
Bowl(3)
Cupboard()
f(2)
f2(1)
f3(1)
由运行结果可以看出,先初始化mail类中的t2,t3.main函数中new Cupboard类的时候,由于在t3中static对象已经初始化一次,所以并不再次初始化,而剩下的所有类均再次初始化。
非静态实例的初始化
1 class Mug { 2 Mug(int marker) { 3 System.out.println("Mug(" + marker + ")"); 4 } 5 void f(int marker) { 6 System.out.println("f(" + marker + ")"); 7 } 8 } 9 public class mail { 10 Mug c1=new Mug(1); 11 Mug c2=new Mug(2); 12 mail() { 13 System.out.println("Mugs()"); 14 } 15 public static void main(String[] args) { 16 System.out.println("Inside main()"); 17 mail x = new mail(); 18 } 19 } ///:
PS:为满足后面的内部匿名化类,需要对此方法进行更改,后待续。
数组的初始化
值得注意的是,java中的数组不允许声明数组大小,这一点与其他语言(c,c++)是不同的。
eg:在java中 int[] i , int i[] 都是可以的,而 int[5] i是不可行的,编译器会报错。
不过可以用关键字“new”来指定大小,比如int[]i=new int[5],这两点特性也被C#所继承。
多维数组:
int[][] i=new int[][];或者int [][] i=new int {{1,2,3}{1,2,3}};
浙公网安备 33010602011771号