无法阻止初始化的自动进行,它将在构造器被调用之前发生。
变量定义的先后顺序决定了初始化的顺序,即使变量定义散布于方法定义之间,它仍旧会在任何方法(包括构造器)之前得到初始化。
import static net.mindview.util.Print.*; // When the constructor is called to create a // Window object, you'll see a message: class Window { Window(int marker) { print("Window(" + marker + ")"); } } class House { Window w1 = new Window(1); // Before constructor House() { // Show that we're in the constructor: print("House()"); w3 = new Window(33); // Reinitialize w3 } Window w2 = new Window(2); // After constructor void f() { print("f()"); } Window w3 = new Window(3); // At end } public class OrderOfInitialization { public static void main(String[] args) { House h = new House(); h.f(); // Shows that construction is done } } /* Output: Window(1) Window(2) Window(3) House() Window(33) f()
静态数据的初始化,看下面这段代码
import static thinkinginjava.Print.*; class Go { static String s1 = "run"; static String s2, s3; static { //静态块或静态句子(首先被执行,且只执行了一次,注意看输出) No.1 s2 = "drive car"; s3 = "fly plane"; print("s2 & s3 initialized"); } static void how() { print(s1 + " or " + s2 + " or " + s3); } Go() { print("Go()"); } } public class ExplicitStaticEx { public static void main(String[] args) { print("Inside main()"); //No.4 Go.how();//No.5 print("Go.s1: " + Go.s1);//No.6 } static Go g1 = new Go(); // No.2 static Go g2 = new Go();//No.3 }//output:
s2 & s3 initialized
Go()
Go()
Inside main()
run or drive car or fly plane
Go.s1: run
如果main方法外的初始化操作不是静态的,即没有static,那么这两句话不会被执行。加上static之后,他们会先于main方法执行,且只会被初始化一次。
构造器可以看作是static方法。
原文地址:http://blog.csdn.net/chaoshenyutou/article/details/44777379