this使用的兩種情況

一、this關鍵字對於將當前對象傳遞給其他方法

/*
 * this關鍵字對於將當前對象傳遞給其他方法
 */
class Person {
public void eat(Apple apple){
Apple peeled=apple.getPeeled();
System.out.println("eat...");
}
}
 class Apple {
Apple getPeeled(){
/*
* this關鍵字對於將當前對象傳遞給其他方法,Apple需要調用Peeler.peel()方法,它是一個外部工具類方法,
* 將執行由於某種原因而必須放在Apple外部的操作。爲了將其自身傳遞給外部方法,Apple必須使用this關鍵字
*/
return Peeler.peel(this);
}
     }
 class Peeler {
static Apple peel(Apple apple){
return apple;
}
}
 public class PassingThis {
public static void main(String[] args) {
new Person().eat(new Apple());
}
}

二、返回對當前對象的引用

/**
 * 返回當前對象的引用
 * @author xieyongxue
 *
 */
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().increment().print();
/*
* 輸出值:i=3
*/
}
}
發佈了91 篇原創文章 · 獲贊 7 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章