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关键字。




猜你喜欢

转载自blog.csdn.net/ccc1234_/article/details/80411881