读书人

this代表什么,该怎么解决

发布时间: 2013-04-02 12:35:26 作者: rapoo

this代表什么
this代表什么
class Person {
public void eat(Apple apple) {
Apple peeled = apple.getPeeled();
System.out.println("Yummy");
}
}

class Peeler {
static Apple peel(Apple apple) {
// ... remove peel
return apple; // Peeled
}
}

class Apple {
Apple getPeeled() { return Peeler.peel(this); }
}

public class PassingThis {
public static void main(String[] args) {
new Person().eat(new Apple());
}
}
[解决办法]
class Apple {
Apple getPeeled() { return Peeler.peel(this); }
}

this 是指Apple对象本身

Apple a = new Apple();
这个时候如何执行下面的语句
a.getPeeled();
效果是这样的
return Peeler.peel(a);

读书人网 >J2SE开发

热点推荐