#1. When local variables and member variables have the same name, use this to represent the member variable in the method to distinguish them
Example:
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 keyword passes the current object to other methods
Example:
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. When you need to return a reference to the current object, you often write return this
in the method. The advantage of this approach is that when you use an object to call this method, the method returns the modified object, and you can use the object to do other operations. Therefore it is easy to perform multiple operations on an object.
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. To call the constructor in the constructor, you need to use this
A class has many constructors. Sometimes you want to use a constructor in a constructor. To call other constructors in a function to avoid code duplication, you can use the this keyword.
Recommended tutorial: Java tutorial
The above is the detailed content of When to use this keyword in java. For more information, please follow other related articles on the PHP Chinese website!