资料来源:
- <Thinking in Java (4th Edition)>
总结一下, 有三种情况:
- this.xxx
- xxx(this)
- this(xxx)
1, this关键字放在方法内部使用, 表示对"调用该方法的那个对象"的引用.
demo:
public class Leaf{
int num = 0;
Leaf increment(){
num++; //隐含为this.num++
return this; //this指代leaf
}
void print(){
System.out.println("num = " + num);
}
public static void main(String[] args){
Leaf leaf = new Leaf();
leaf.increment().increment().increment().print();
}
}
2, this关键字放在方法参数列表中, 可将当前对象传递给其他方法.
demo:
public class run{
public static void main(String[] args){
new Person().eat(new Apple());
}
}
class Person{
public void eat(Apple apple){
Apple peeled_apple =
apple.getPeeled();
System.out.println("peeled apple is delicious!");
}
}
class Apple{
Apple getPeeled(){
//调用getPeeled()的是上面的apple, 所以, 这里的this指代上面的apple.
return Peeler.peel(
this); //对象传递.
}
}
class Peeler{ //削皮刀
static Apple peel(Apple apple){
...; //一系列削皮操作
return apple; //peeled
}
}
3, this关键字在构造器中调用构造器.
public class Constructor {
private String str1;
private String str2;
Constructor(String str){
this(str, "world"); //一个参数的构造器调用两个参数的构造器.
System.out.println(str);
}
Constructor(String str1, String str2) {
this.str1 = str1;
this.str2 = str2;
System.out.println(str1 + " " +str2);
}
public static void main(String[] args) {
Constructor c = new Constructor("hello");
}
}
注:
- 可以在构造器中使用this关键字调用其他构造器, 但只能调用一个. 即下面的情况是错的:
Constructor(){
this("world");
this("hello", "world"); //
错误, 在构造器中只能调用一个其他构造器.
}
- 对其他构造器的调用只能在当前构造器的第一行.
Constructor(String str){
this.str = str;
this(str, "world"); //
错误, 此构造器下的第一行.
}
- 只能在构造器中调用其他构造器, 一般方法不可调用构造器.