this关键字
假设你希望在方法的内部获得对当前对象的引用,可以使用this关键字。this关键字只能在方法内部使用,表示对“调用方法的那个对象”的引用,在如果在一个方法的内部调用同一个类的其他方法,则直接调用即可。
用处:
- 当需要返回当前对象的引用时,常常在return语句中写即可。
- this关键字用于将当前对象传递给其他方法:
class Person { public void eat(Apple apple) { Apple peeled = apple.getPeeled(); } } class Peeler { static Apple peel(Apple apple){ //... remove peel return apple } } class Apple{ Apple getPeeled(){ return Peeler.peel(this) } }
Apple类中,把调用getPeeled()方法的对象的引用通过this关键字传递给Peeler里的方法。
- 在构造器中调用构造器
public class Flower { Flower(String ss) { //... } Flower(int petals){ //... } Flower(String ss, int petals){ this(petals); //调用了上面的构造器 // this(ss); //不可以!不能调用两个 this.ss = " "; } }
这样做可以节省代码!
详见<Thinking in java> P84 : 5.4 this关键字

浙公网安备 33010602011771号