This关键字
this关键字只能在方法内部使用,表示对调的方法的那个对象的引用
public class Test{
int i = 0;
Test increment(){
i++;
return this; //返回对当前对象的引用
}
void print(){
System.out.println(i);
}
public static void main(String[] args) {
Test t = new Test();
t.increment().increment().increment().print();
}
}
class Person{
public void eat(Apple apple){
Apple peeled = apple.getPeeled();
Apple peeled1 = apple.getPeeled();
System.out.println(peeled.equals(peeled1));
}
}
class Peeler{
static Apple peel(Apple apple){
return apple;
}
}
class Apple{
Apple getPeeled(){ //无参数 只能使用this才能确保传递的是同一个对象
return Peeler.peel(this);
}
}
public class ThreadTest {
public static void main(String[] args) {
new Person().eat(new Apple());
//输出为true
}
}