首页 > 编程语言 > 详细

Java:this示例2

时间:2015-04-19 00:58:43      阅读:299      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!