据我所知,this有三个用途,但this都表示当前对象自身。
一、访问当前对象的数据域
public class TestThis {
public int age;
public TestThis() {
age = 1;
}
public TestThis(int age) {
this.age = age;
}
}
当构造方法传入的变量的变量名和当前对象数据域中的变量名一样时,可以使用 this 来访问当前对象数据域的变量。
二、调用当前对象的构造方法
public class TestThis {
public int age;
public String name;
public char sex;
public TestThis() {
sex = 'm';
}
public TestThis(String name) {
this();
this.name = name;
}
public TestThis(int age) {
this();
this.age = age;
}
public TestThis(String name, int age) {
this(name);
this.age = age;
}
public static void main(String[] args) {
TestThis testThis = new TestThis("PIGGY", 18);
System.out.println("name:" + testThis.name + "\nage:" + testThis.age +
"\nsex:" + testThis.sex);
}
}
输出结果为:
name:PIGGY
age:18
sex:m
这个用法需要注意:
(1)在一个构造方法中可以使用 this(); 来调用另一个构造方法,但不可以调用两个。
(2)必须将构造方法的调用放在方法的起始位置,不然会报错。
三、返回当前对象自身
public class TestThis {
public int number;
public TestThis() {
number = 0;
}
TestThis returnSelf() {
number++;
return this;
}
public static void main(String[] args) {
TestThis testThis = new TestThis();
System.out.println("返回次数:" + testThis.returnSelf().returnSelf().returnSelf().number);
}
}
输入结果为:
返回次数:3
这里的 this 放回的是当前对象本身,所以 testThis.returnSelf() 是个 TestThis 对象,它也有自己的 number 变量和 returnSelf() 方法,以此类推 testThis.returnSelf().returnSelf().returnSelf() 也是一个 TestThis 对象,它也有自己的 number 。