1. this产生一个调用该方法的当前对象的引用
当我们在类中调用类中的另一个方法时,我们不需要显式使用this关键字的。我们只需直接调用方法,this关键字将自动作用于调用的方法。所以如下代码中pit()方法不需要在调用pick()时使用this.pick();
public class Apricot{
void pick(){
//code here...
}
void pit(){
pick();
//code here;
}
}
2. this传递当前对象的引用给当前方法
public class Leaf{
int i = 0;
Leaf increment(){
i++;
return this;
}
void print(){
System.out.println("i = "+I );
}
public static void main(String[] args){
Leaf leaf = new Leaf();
leaf.increment().increment().print();
}
}
3. this 传递当前对象的引用给其他方法
public class PassingThis{
public static void main(String[] args){
new Person().eat(new Apple());
}
}
class Person{
public void eat(Apple apple){
Apple peeled = apple.getPeeled();
System.out.println(peeled.hashCode()+" Yummy!");
}
}
class Apple{
public Apple getPeeled(){
return Peeler.peel(this);
}
}
class Peeler{
public static Apple peel(Apple apple){
return apple;
}
}
4. this用于构造函数中,用来调用其他构造函数
class Tree{
private int height;
private String name;
public Tree(int height){
this.height = height;
}
public Tree(String name){
this.name = name;
}
//'this' can be used to invoke another constructor, but it has to be the first sentence.
public Tree(int height, String name){
this(height);
this.name = name;
}
}