码迷,mamicode.com
首页 > 编程语言 > 详细

Java:this示例2

时间:2015-04-19 01:01:56      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:

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.

Java:this示例2

标签:

原文地址:http://www.cnblogs.com/taoxiuxia/p/4438496.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!