类中静态域、块,非静态域、块,构造函数的初始化顺序
在《Core java 2: volumn 1, Edion 5》一书的第四章“对象与类”中讲到域赋值语句、实例块、
静态块及构造方法等在创建类实例时的执行顺序,中文译本有些处翻译的不贴切,而英文
原书中也有一 处错误。本文通过一个小程序来说明类实例构造过程中的语句执行顺序。
public class Teststaticblock {
public Teststaticblock() {
this("second");
System.out.println("begin constructor");
System.out.println(s_a);
System.out.println(s_b);
System.out.println(c);
System.out.println(d);
// this("second");//call to this must be first statement in
constructor
s_a = 1111;
s_b = 2222;
c = 3333;
d = 4444;
System.out.println(s_a);
System.out.println(s_b);
System.out.println(c);
System.out.println(d);
System.out.println("end constructor");
}
public Teststaticblock(String s) {
System.out.println("begin second constructor");
System.out.println("end second constructor");
}
/*
* 2nd initialized
*/
public static void main(String args[]) {
System.out.println("begin main");
System.out.println(s_a); // initialize in 1st
System.out.println(s_b); // initialize in 1st
// System.out.println(c);//non-static variable c cannot be
referenced from a static context
// System.out.println(d);//non-static variable c cannot be
referenced from a static context
s_a = 11111;
s_b = 22222;
// c=33333;//non-static variable c cannot be referenced from
a static context
// d=44444;//non-static variable c cannot be referenced from
a static context