Java:this示例2

The this keyword is also useful for passing the current object to another method:

 1 class Person {
 2     public void eat(Apple apple) {
 3         Apple peeled = apple.getPeeled();
 4         System.out.println("Yummy");
 5     }
 6 }
 7 
 8 class Peeler {
 9     static Apple peel(Apple apple) {
10         // ...remove peel
11         return apple;// Peeled
12     }
13 }
14 
15 class Apple {
16     Apple getPeeled() {
17         return Peeler.peel(this);
18     }
19 }
20 
21 public class PassingThis {
22     public static void main(String[] args) {
23         new Person().eat(new Apple());
24     }
25 }

输出

Yummy

Apple needs to call Peeler.peel(),which is a foreign utility method that performs an operation that,for some reason,needs to be external to Apple(perhaps the external method can be applied across many different classes, and you  donnot want to repeat the code). To pass itself to the foreign method, it must use this.

posted @ 2015-04-19 00:49  陶修瑕  阅读(119)  评论(0编辑  收藏  举报