this只存在于方法内部,用来代表调用改方法的对象。可以理解为每一个方法内部都有一个局部变量叫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("这是局部变量"); }}
2、this关键字把当前对象传递给其他方法
实例:
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()); }}
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(); }}结果为:4
4、在构造器中调用构造器需要使用this
一个类有许多构造函数,有时候想在一个构造函数中调用其他构造函数,以避免代码重复,可以使用this关键字。
推荐教程:java教程
以上就是java中什么时候用this?的详细内容。