zoukankan      html  css  js  c++  java
  • 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.

  • 相关阅读:
    投产包错误的思考
    Oracle----用户操作
    3.27 学习记录
    3.26 学习记录
    3.25 学习记录
    3.24 学习记录
    3. 23构建之法读后感
    3.22 学习记录
    3. 21学习记录
    3.20 学习记录
  • 原文地址:https://www.cnblogs.com/taoxiuxia/p/4438496.html
Copyright © 2011-2022 走看看