执行下段代码:
1 public class Practice { 2 public static void main(String[] args) { 3 InitalizeBlockClass obj = new InitalizeBlockClass(); 4 System.out.println(obj.field); 5 6 obj = new InitalizeBlockClass(300); 7 System.out.println(obj.field); 8 } 9 } 10 class InitalizeBlockClass{ 11 //public int field = 100; 若该语句写在这里,第一次输出值为200 12 { 13 field = 200; 14 } 15 public int field = 100; 16 public InitalizeBlockClass(int value) { 17 this.field = value; 18 } 19 public InitalizeBlockClass() { 20 21 } 22 }
如代码所示,100(定义)写在200(初始化块)后面,最终执行结果是100,当二者顺序对调时,输出结果是200。因此,在执行Java代码时,类字段初始化时,成员定义默认值与初始化块,执行哪一个需要看其顺序,最终执行是排在后面的那个;第二次输出是调用了有参数的构造方法,因此类字段初始化关于构造方法执行时,只需要根据声明时是否带有参数判断执行哪一个构造方法,再执行即可。