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.

转载于:https://www.cnblogs.com/taoxiuxia/p/4438496.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值