this is an implicit pointer to itself. Simply put, which object calls the method where this is located, then this is that object.
Sample code: TestThis_1.java
Copy the code code as follows:
/* Question: What is this
* Output result:
* A@4e44ac6a
*/
public class TestThis_1 {
public static void main(String[] args) {
A aa = new A();
System.out.println(aa.f()); //aa.f(), returns the reference (pointer) of the object aa
}
}
class A {
public A f() {
return this; //Return a reference to the class A object of the object that calls the f() method
}
}
Common uses of this
1. Distinguish variables with the same name
Sample code: TestThis_2.java
Copy the code code as follows:
/* Common usage of this 1: Distinguish variables with the same name
* Output result:
* this. i = 1
* i = 33
*/
public class TestThis_2 {
public static void main(String[] args) {
A aa = new A(33);
}
}
class A {
public int i = 1; //This i is a member variable
/*Note: Generally not written like this, the constructor is mainly for initialization, and written like this is mainly for ease of understanding*/
public A(int i) { //This i is a local variable
System.out.printf("this. i = %d/n", this.i); //this.i refers to the member variable i of the object itself
System.out.printf("i = %d/n", i); //i here is local variable i
}
}
2. Mutual calls between constructors
Sample code: TestThis_3.java
Copy the code code as follows:
/* Common usage of this 2: calling each other in the constructor */
public class TestThis_3 {
public static void main(String[] args) {
}
}
class A {
int i, j, k;
public A(int i) {
this.i = i;
}
public A(int i, int j) {
/* i = 3; error If not commented out, an error will be reported: When calling the constructor with this(...), it can only be placed in the first sentence
* TestThis_3.java:20: error: call to this must be first statement in constructor
* this(i);
* ^
*1 error
*/
this(i);
this.j = j;
}
public A(int i, int j, int k) {
this(i, j);
this.k = k;
}
}
Things to note
Methods modified by static do not have this pointer. Because the method modified by static is public, it cannot be said which specific object it belongs to.
Sample code: TestThis_4.java
Copy the code code as follows:
/*There is no this pointer inside the static method*/
public class TestThis_4 {
public static void main(String[] args) {
}
}
class A {
static A f() {
return this;
/* Error message: TestThis_4.java:10: error: non-static variable this cannot be referenced from a static context
* return this;
* ^
*1 error
*/
}
}