package test2; public class InitializeBlockDemo { /** * @param args */ public static void main(String[] args) { InitializeBlockClass obj=new InitializeBlockClass(); System.out.println(obj.field); obj=new InitializeBlockClass(300); System.out.println(obj.field); } } class InitializeBlockClass{ //下面这句在初始化块之前与之后,会影响到field字段的初始值 public int field=100; { field=200; } //public int field=100; public InitializeBlockClass(int value){ this.field=value; } public InitializeBlockClass(){ } }
结果:
200 300
package test2; public class InitializeBlockDemo { /** * @param args */ public static void main(String[] args) { InitializeBlockClass obj=new InitializeBlockClass(); System.out.println(obj.field); obj=new InitializeBlockClass(300); System.out.println(obj.field); } } class InitializeBlockClass{ //下面这句在初始化块之前与之后,会影响到field字段的初始值 //public int field=100; { field=200; } public int field=100; public InitializeBlockClass(int value){ this.field=value; } public InitializeBlockClass(){ } }
结果:
100 300
类成员定义时指定的默认值和初始化块会由前到后依次执行,主要看它们在类中的前后顺序,然后在进行类的构造方法
标签:初始化,InitializeBlockClass,Java,int,field,字段,obj,100,public From: https://www.cnblogs.com/ashuai123/p/16749508.html