在构造器中,为this添加参数列表,即可形成对符合此参数列表的某个构造器的明确调用。
例:
public class Flower {
int petalCount=0;
String s="initial value";
Flower(int petals){
petalCount=petals;
System.out.println("Constructor w/ int args only, petalCount = "+petalCount);
}
Flower(String ss){
System.out.println("Constructor w/ String args only, s = "+ss);
s=ss;
}
Flower(String s, int petals){
this(petals);
// this(s); //Can't call two!
this.s=s;
System.out.println("String & int args");
}
Flower(){
this("hi", 47);
System.out.println("default constructor (no args)");
}
void printPetalCount(){
// this(11); //Not inside non-constructor!
System.out.println("petalCount = "+petalCount+" s = "+s);
}
public static void main(String[] args) {
Flower x= new Flower();
x.printPetalCount();
}
}
Output:
Constructor w/ int args only, petalCount = 47
String & int args
default constructor (no args)
petalCount = 47 s = hi
注意第16行,这表明必须在构造器中第一个声明中调用另一个构造器,且只能调用一个其他的构造器。