Thinking in java-18 this 关键字

1. this产生一个调用该方法的当前对象的引用

当我们在类中调用类中的另一个方法时,我们不需要显式使用this关键字的。我们只需直接调用方法,this关键字将自动作用于调用的方法。所以如下代码中pit()方法不需要在调用pick()时使用this.pick();

public class Apricot{
    void pick(){
        //code here...
    }
    void pit(){
        pick();
        //code here;
    }
}

2. this传递当前对象的引用给当前方法

public class Leaf{
    int i = 0;
    Leaf increment(){
        i++;
        return this;
    }
    void print(){
        System.out.println("i = "+I );
    }
    public static void main(String[] args){
        Leaf leaf = new Leaf();
        leaf.increment().increment().print();
    }
}

3. this 传递当前对象的引用给其他方法

public class PassingThis{
    public static void main(String[] args){
        new Person().eat(new Apple());
    }
}
class Person{
    public void eat(Apple apple){
        Apple peeled = apple.getPeeled();
        System.out.println(peeled.hashCode()+" Yummy!");
    }
}
class Apple{
    public Apple getPeeled(){
        return Peeler.peel(this);
    }
}
class Peeler{
    public static Apple peel(Apple apple){
        return apple;
    }
}

4. this用于构造函数中,用来调用其他构造函数

class Tree{
    private int height;
    private String name;
    public Tree(int height){
        this.height = height;
    }
    public Tree(String name){
        this.name = name;
    }
    //'this' can be used to invoke another constructor, but it has to be the first sentence.
    public Tree(int height, String name){
        this(height);
        this.name = name;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值