java中初始化的顺序

来源:互联网 发布:复制信息淘宝怎么打开 编辑:程序博客网 时间:2024/05/17 21:30
1.初始化的顺序
 
对类而言,初始化的顺序是由变量在类的定义里面的顺序决定的,变量的定义可能会分散在类定义的各个地方,并且与方法的定义相互交错,但是变量的初始化会先于任何方法,甚至是构造函数的调用。
 
class Tag {
  Tag(int marker) {
    System.out.println("Tag(" + marker + ")");
  }
}
class Card {
  Tag t1 = new Tag(1); // Before constructor
  Card() {
    // Indicate we're in the constructor:
    System.out.println("Card()");
    t3 = new Tag(33); // Reinitialize t3
  }
  Tag t2 = new Tag(2); // After constructor
  void f() {
    System.out.println("f()");
  }
  Tag t3 = new Tag(3); // At end
}
public class Flower {
  public static void main(String[] args) {
    Card t = new Card();
    t.f(); // Shows that construction is done
  }
}
 
输出结果如下:
Tag(1)
Tag(2)
Tag(3)
Card()
Tag(33)
f()
 
2.静态数据的初始化
 
无论创建多少对象,static数据只能有一份。它的初始化不是在定义的时候进行的。
 
class Bowl {
   Bowl(int marker) {
     System.out.println("Bowl(" + marker + ")");
   }
   void f(int marker) {
     System.out.println("f(" + marker + ")");
   }
}
class Table {
   static Bowl b1 = new Bowl(1);
   Table() {
     System.out.println("Table()");
     b2.f(1);
   }
   void f2(int marker) {
     System.out.println("f2(" + marker + ")");
   }
   static Bowl b2 = new Bowl(2);
}
class Cupboard {
   Bowl b3 = new Bowl(3);
   static Bowl b4 = new Bowl(4);
   Cupboard() {
     System.out.println("Cupboard()");
     b4.f(2);
   }
   void f3(int marker) {
    System.out.println("f3(" + marker + ")");
  }
  static Bowl b5 = new Bowl(5);
}
public class E1 {
  public static void main(String[] args) {
    System.out.println("Creating new Cupboard() in main");
    new Cupboard();
    System.out.println("Creating new Cupboard() in main");
    new Cupboard();
   Table t2 = new Table();
 Cupboard t3 = new Cupboard();
    t2.f2(1);
    t3.f3(1);
  }
}
 
程序的输出如下:
 
Creating new Cupboard() in main
Bowl(4)
Bowl(5)
Bowl(3)
Cupboard()
f(2)
Creating new Cupboard() in main
Bowl(3)
Cupboard()
f(2)
Bowl(1)
Bowl(2)
Table()
f(1)
Bowl(3)
Cupboard()
f(2)
f2(1)
f3(1)
 
从程序的输出可以看出,static成员只会在需要的时候进行初始化。如果没有创建Table对象,就永远不可能用到Table.b1或者Table.b2,因此也不会去创建static的Bowl b1和b2。只有创建了第一个Table对象之后(或者第一次访问static成员的时候),它们才会被初始化。此后,static对象就不会再作初始化了。 
 

 
 
原创粉丝点击