This keyword is a concept that I think is very difficult to understand in Java. :) Maybe it is because it is too stupid
The meaning of this keyword: a corresponding handle can be generated for the object whose method is called.
How do you understand this passage?
There is such an example in thinking in java
There are two objects of the same type, called a and b, respectively. So how do we distinguish between who calls this method when calling method f()?
For example:
class Banana {void f(int i) {/*** method body*****/}} Banana a = new Banana();//generate Banana object aBanana b= new Banana();//generate Banana object ba.f(1);bf(2);So how does the compiler know which object's f() function you are calling? In fact, the behind-the-scenes teleportation should be:
af(1)<<====>>Banana.f(a,1);bf(1)<<====>>Banana.f(b,2);
I understand it as: when generating a Banana object a. When calling a method f() of a, a handle pointing to this object will be generated at the same time.
Here is this pointing object new Banana() or this is equivalent to handle a; this "==" a;
When we are inside a method. And we hope to get the handle of the current object. Since this handle is secretly passed by the compiler, there is no clear symbol to identify it. At this time, we can use the keyword this
The common meaning of this: no matter which object generated calls this method, a pointer to this object will be generated.
Classic examples in thinking in java:
public class Leaf{private int i=0;Leaf increment(){i++;return this;}void print(){Systme.out.println("i="+i);public static void main (String [] args){Leaf x =new Leaf();x.increment().increment().increment().increment();}}1. Generate the handle x of an object; the syntax format is Leaf x;
2. Generate a Leaf class object; the syntax format is new Leaf();
3. Establish a connection between the handle and the object; the syntax is x = new Leaf();
4. Call the method increment() in the object new Leaf(); the syntax is x.increment()
×××Who called the method increment()? It is an object x (or new Leaf()) of the Leaf class, so the corresponding system will generate a reference this and secretly point it to x or new Leaf() object, so increment() returns a reference to x! It is a memory address. We can print it out and see it!
The above content is the knowledge of this keyword in Java introduced to you by the editor. I hope it will be helpful to you!