构造代码块优于构造函数执行,且可以对多个对象进行初始化;构造函数只能根据参数对一个对象进行初始化。
public class test1
{
int number;
int times;
String name;
public test1(){}
public test1(int times)
{
System.out.println("执行构造函数1");
this.times = times;
}
public test1(int number,int times,String name)
{
System.out.println("执行构造函数2");
this.number = number;
this.times = times;
this.name = name;
}
{
System.out.println("执行构造代码块");
number = 7;
name = "xu";
}
public static void main(String[] args)
{
test1 test = new test1();
System.out.println(test.number);
test1 tes = new test1(1);
System.out.println(tes.number);
System.out.println(tes.times);
test1 te = new test1(1,1,"wei");
System.out.println(te.number);
}
}
运行结果如下 :