今天在《thinking in java》上面看了关于初始化问题,之前从来都没有深入考虑过,这次算是把它搞明白了,所以记录一下:

这个不是我看到的初始化顺序问题,在网上搜索的时候发现的,感觉讲得很好,就收下了:http://www.cnblogs.com/miniwiki/archive/2011/03/25/1995615.html

我看的是静态数据和非静态数据的初始化,总结比较重要的内容:

1.在类的内部,变量定义的先后顺序决定了初始化的顺序。即使变量定义散步于方法定义间,它们仍旧会在任何方法(包括构造器)被调用之前得到初始化。

2.无论创建多少个对象,静态数据都只占用一份存储区域。static关键字不能应用与局部变量,因此它只能作用于域。如果一个域是静态的基本类型域,且也没有对它进行初始化,那么它就会获得基本类型的标准初值;如果它是一个对象的引用,那么它的默认初始化值就是null。

 1 //: initialization/OrderOfInitialization.java
 2 // Demonstrates initialization order.
 3 import static net.mindview.util.Print.*;
 4 
 5 // When the constructor is called to create a
 6 // Window object, you'll see a message:
 7 class Window {
 8   Window(int marker) { print("Window(" + marker + ")"); }
 9 }
10 
11 class House {
12   Window w1 = new Window(1); // Before constructor
13   House() {
14     // Show that we're in the constructor:
15     print("House()");
16     w3 = new Window(33); // Reinitialize w3
17   }
18   Window w2 = new Window(2); // After constructor
19   void f() { print("f()"); }
20   Window w3 = new Window(3); // At end
21 }
22 
23 public class OrderOfInitialization {
24   public static void main(String[] args) {
25     House h = new House();
26     h.f(); // Shows that construction is done
27   }
28 } /* Output:
29 Window(1)
30 Window(2)
31 Window(3)
32 House()
33 Window(33)
34 f()
35 *///:~
View Code

相关文章: