this用在类内部,表示类实例本身。
this关键字是类内部当中对自己的一个引用,可以方便类中方法访问自己的属性。
java中this用法
1、当局部变量和成员变量重名的时候,在方法中使用this表示成员变量以示区分。
class Demo{ String str = "这是成员变量"; void fun(String str){ System.out.println(str); System.out.println(this.str); this.str = str; System.out.println(this.str); }}public class This{ public static void main(String args[]){ Demo demo = new Demo(); demo.fun("这是局部变量"); }}
分析:上面的类Demo中有一个成员变量str和一个局部变量str(类方法中的形式参数),很显然局部变量和成员变量重名,这个时候一般在方法中直接使用str实际上是使用局部变量str,对成员变量str没有任何影响,此时如果需要对成员变量做点什么,就必须使用this关键字。
有个问题,如果方法中没有str,那么在方法中使用成员变量str会是什么情况呢?实际上是方法内的所有操作都是针对成员变量str的。java编程思想的84页中部有这样一句话:如果在方法内部调用同一个类的另一个方法,就不必使用this。同样,在一个方法中如果没有局部变量和成员变量同名,那么在这个方法中使用成员变量也不必使用this,可以运行下面的代码看看。
class Demo{ String str = "这是成员变量"; void fun(String str1){ System.out.println(str1); System.out.println(str); }}public class This{ public static void main(String args[]){ Demo demo = new Demo(); demo.fun("这是局部变量"<strong>本文来源gao@daima#com搞(%代@#码@网2</strong>); }}
2、this关键字把当前对象传递给其他方法
这里有个很经典的例子,就是java编程思想的85页的例子。我们拿出来仔细研究。
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; }}class Apple{ Apple getPeeled(){ return Peeler.peel(this); }}public class This{ public static void main(String args[]){ new Person().eat(new Apple()); }}
这是我自己的认识,也许不正确,看看书中是怎样说的:Apple需要调用Peeler.peel()方法,他是一个外部的工具方法,将执行由于某种原因而必须放在Apple外部的操作(也许是因为该外部方法要应用于许多不同的类,而你却不想重复这些代码)。为了将其自身传递给外部方法,必须使用this关键字。
分析:设想一个场景,假如各种水果去皮的工作都是一样的,只要给我水果,我都按同样的方法去皮。那么结合上面的例子,传进来一个水果,我们吃之前getPeeled(),必须将此水果作为参数传递给外部的peel(),用this来代表自身传递给外部方法。
3、当需要返回当前对象的引用时,就常常在方法写return this;
这种做法的好处是:当你使用一个对象调用该方法,该方法返回的是经过修改后的对象,且又能使用该对象做其他的操作。因此很容易对一个对象进行多次操作。
public class This{ int i = 0; This increment(){ i += 2; return this; } void print(){ System.out.println("i = " + i); } public static void main(String args[]){ This x = new This(); x.increment().increment().print(); }}