Java 中 this 关键字的作用

最近在阅读他人代码的时候发现同事中有好些喜欢用this.XXX。我对这种无一例外都加上this关键字的做法是不认同的,因为程序应该简洁明了,很多时候不用加this关键字便没有这个必要,反而会让后来者看程序看的头疼。因此搞清楚this关键字在哪些时候必须使用是很有必要的。在《Java编程思想》这本书中写道this的关键作用有两个,我分别对这两个关键作用做一个总结。

1、需要明确指出对当前对象的引用时,需要使用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 x = new Leaf();
    x.increment().increment().increment().print();
  }
}

 

输出结果为3。因为increment()方法返回的是当前对象的引用,这时必须使用this关键字。

 

2、将当前对象传递给其他方法时,需要使用this关键字

例如以下程序:

public class Test {
    static class Apple {
         Apple getPeeled() {
            return Peeler.peel(this);
        }
    }
    static class Peeler {
        static Apple peel(Apple apple) {
            return apple;
        }
    }

    static class  Person {
        public void eat(Apple apple) {
            Apple peeled = apple.getPeeled();
            System.out.println("Yummy");
        }
    }

    public static void main(String args[]) {
        new Person().eat(new Apple());
    }

}

程序中,Apple要调用Peeler的peel()方法,由于这是一个外部方法,因此需要将自身传递个给外部方法就需要使用this关键字。

 

 

 

 

 

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值