使用this在构造器中调用构造器,通常写this的时候,都是指“这个对象”或者“当前对象”,而且它本身表示对当前对象的引用。在构造器中,如果为this添加了参数列表,那么就有了不同的含义。这将产生对符合此参数列表的某个构造器的明确调用;这样,调用其他构造器就有了直接的途径:
Java代码
public class Flower{
int petalCount=0;
String s="initial value";
Flower(int petals){
petalCount=petals;
System.out.print("Constructor w/int arg only,petalCount=.."+petalCount);
}
Flower(String ss){
System.out.print("Constructor w/String arg only,s="+ss);
s=ss;
}
Flower(String s,int petals){
this(petals);
this(s); //Can't call two!
this.s=s; //Another use of"this"
System.out.print("String&int args");
}
public void printPetel(){
// this(11);
System.out.print(
"petalCount=.."+petalCount+ "s="+ss);
}
}
注:printPetel()方法表明,除构造器之外,编译器禁止在其他任何方法中调用构造方法。