通常,this指针指的是调用此方法的当前对象,且是可缺省的,一般只有当参数名与数据成员名相同时,才需要this关键字来避免歧义。但是,如果为this提供了参数列表,那么即意味着对符合该参数列表的构造器的调用。
通过this关键字调用构造器有以下几条规范:
- 不能在普通方法中调用,只能在构造器中调用。
- 一个构造器中只能调用一次。
- 只能在构造器的第一行调用。
代码:
public class test4 {
public test4(int a,int b,int c){
this(a,b);
//this(a); //此行报错,意味着在一个构造器里面只能调用一次构造器。
}
public test4(int a,int b) {
this(a);
}
public test4(int a){
System.out.println("调用成功!");
}
public test4(){
int a;
//this(a); //此行报错,且提示:构造器的调用必须在一个构造器的第一行
}
public void TestThis(){
//this(1); //此行报错,且提示:构造器的调用必须在一个构造器的第一行
}
public static void main(String[] args) {
new test4(1, 2, 3); //调用成功,意味着虽然一个构造器中只能调用一次其它构造器,但却可以通过“一个调一个”的方式调用多个构造器。
}
}
结果: