构造器无法阻止自动初始化的运行,它将在构造器被调用之前发生. class Counter{ int i; Counter(){i = 7;} } i首先会被置0,然后变成7.对于所有基本类型和对象引用,包括在定义时已经指定初值的变量,这种情况都是成立的.因此编译器不会强制你一定要在构造器中or在使用它们之前对元素进行初始化. 初始化顺序:在类的内部,变量定义的先后顺序决定了初始化的顺序.即使变量定义散布于方法定义之间,它们仍旧会在任何方法(包括构造器)被调用之前得到初始化. 静态数据的初始化:情况并无不同.注意:只有在第一个对象被创建(或第一次访问静态数据)的时候,静态对象才会被初始化.此后,静态对象不会再次被初始化. 初始化的顺序是,先"静态"对象(如果它们尚未因前面的对象创建过程而被初始化),而后是"非静态"对象,再执行构造器(此时可能会牵涉到很多动作,尤其是涉及继承的时候).
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 ); }
/**/
/* Cupboard类执行顺序:1.static成员,2.非static变量or对象实例化的初始化,3.其它(看运行结果可理解) */
class
StaticInitialization
...
{ 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(); t2.f2( 1 ); t3.f3( 1 ); } static Table t2 = new Table(); static Cupboard t3 = new Cupboard(); }
Java允许将多个静态初始化动作组织成一个特殊的"静态块".与其他静态初始化动作一样,当类被装载时,"静态块"执行,且这段代码仅执行一次. 当一个程序中用到了其他的类,类是在第一次被使用的时候才被装载,而不是在程序启动时就装载程序中所有可能用到的类. 无论是执行(1)代码访问静态的c1对象还是(2)代码访问静态的c1对象,Cups的静态初始化动作都会得到执行(标号(2)中代码激活一行or两行代码都无关紧要,因为静态初始化动作只进行一次). Java中也有类似语法,用来初始化每一个对象的非静态变量(只需要将"静态块"前的static去掉就ok了).
class
Cup
...
{ Cup( int marker) ... { System.out.println( " Cup( " + marker + " ); " ); } void f( int marker) ... { System.out.println( " f( " + marker + " ); " ); } }
class
Cups
...
{ static Cup c1; static Cup c2; static ... { c1 = new Cup( 1 ); c2 = new Cup( 2 ); System.out.println( " static code block " ); } Cups()... { System.out.println( " Cups " ); } }
class
ExplicitStatic
...
{ public static void main(String[] args) ... { System.out.println( " Inside main() " ); // Cups.c1.f(99); (1) } // static Cups x = new Cups(); (2) // static Cups y = new Cups(); }