Java learning notes -- understanding of this keyword, learning notes -- this
Thoroughly understand the meaning of this keyword
This keyword is another concept in java that I think is very difficult to understand. :) maybe it is too stupid.
Meaning of this Keyword: a corresponding handle can be generated for the object whose method is called.
How can we understand this passage?
Thinking in java has such an example
There are two objects of the same type, called a and B respectively. How do we distinguish who calls this method when calling method f?
For example:
Class Banana {
Void f (int I ){
/***** Method subject *****/
}
}
Banana a = new Banana (); // generate Banana object
Banana B = new Banana (); // generate Banana object B
A. f (1 );
B. f (2 );
Then how does the compiler know which object you want to call the f () function? In fact, the transfer behind the scenes should be:
A. f (1) <<===> Banana. f (a, 1 );
B. f (1) <<===> Banana. f (B, 2 );
I understand that: when a Banana object a is generated and the method f () of a is called, a handle pointing to this object is generated at the same time. this
Here is this pointing to the object new Banana () or this here is equivalent to handle a; this "=";
When we are inside a method. In addition, we want to obtain the handle of the current object. Because the compiler secretly transmits the handle, there is no clear identifier to identify it. In this case, we can use the keyword "this ".
The common meaning of this: no matter which object is generated to call this method, a pointer to this object will be generated.
Typical Example of thinking in java:
Public class Leaf {
Private int I = 0;
Leaf increment (){
I ++;
Return this;
}
Void print (){
When me. out. println ("I =" + I );
Public static void main (String [] args)
{
Leaf x = new Leaf ();
X. increment (). print ();
}
}
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. Create a connection between the handle and the object. The syntax is x = new Leaf ();
4. Call the method increment () in the new Leaf () object. The syntax is x. increment ()
××× Who called the method increment? Is the Leaf class Object x (or new Leaf (), so the corresponding system will generate a this reference and secretly point it to x or to the new Leaf () object, therefore, increment () returns a reference pointing to x! It is a memory address. We can print it out and see it!