一个类写了多个构造器,有时可能想在一个构造器中调用另一个构造器,以避免重复代码,可用this关键字做到这一点。
通常写this的时候,都是指“这个对象”或者“当前对象”,而且它本身表示对当前对象的引用。在构造器中,如果为this添加了参数列表,那么就有了不同含义。这将产生对符合此参数列表的某个构造器的明确调用;这样,调用其他构造器就有了直接的途径。
public class Flower{
int petalCount = 0;
String s = "initial value";
Flower(String ss){
system.out.println("Constructor int arg only,petalCount= "+petalCount);
}
Flower(String s,int petals){
this(petals);
// this(s); //Can't call two!
this.s = s; //Another use of "this"
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();
}
}
打印信息:
Constructor int arg only,petalCount= 47
String & int args
default constructor (no args)
petalCount = 47 s = hi
构造器Flower(String s,int petals) 表明: 尽管可以用this调用一个构造器,但是不能调用两个。此外,必须将构造器调用置于最起始处,否则编译器会报错。
这个例子也展示了this的另一种用法。由于参数s的名称·和数据成员s的名字相同,所以会产生歧义,使用this.s来代表数据成员就能解决这个问题。
printPetalCount()方法表明,除构造器之外,编译器禁止在其他任何方法中调用构造器。