目标:进一步了解自由块的运行机制
源文件:Person.java
package cn.com.Person;
public class Person {
String name;
int age;
String sex;
public Person(){
System.out.println("构造器Person()被调用");
sex = "Male";
System.out.println("name=" + name +" age="+age+" sex="+sex);
}
public Person(String TheName){
//调用构造器Person()
this();
System.out.println("构造器Person(String TheName)被调用");
name = TheName;
System.out.println("name=" + name +" age="+age+" sex="+sex);
}
public Person(String TheName,int TheAge){
//调用构造器Person()
this(TheName);
System.out.println("构造器Person(String TheName,int TheAge)被调用");
age = TheAge;
System.out.println("name=" + name +" age="+age+" sex="+sex);
}
{
name = "小明";
age = 20;
sex = "Female";
System.out.println("初始化后:"+"name=" + name +" age="+age+" sex="+sex);
}
}
源文件:TestPerson.java
/*
* author guojing
* e-mail guo443193911@126.com
*
*/
package cn.com.Person;
public class TestPerson {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Person person = new Person();
}
}
编译执行上面的程序,结果如下:
初始化后:name=小明 age=20 sex=Female
构造器Person()被调用
name=小明 age=20 sex=Male
可以看到,初始化(自由块)会先与构造器调用执行。
阅读(461) | 评论(0) | 转发(0) |