Thoroughly understand the meaning of this keyword
This keyword is a concept that I think is very difficult to understand, and it may be the reason for being too stupid.
This keyword means that the appropriate handle can be generated for the object that has called its method.
How do you understand this passage?
Thinking in Java has an example
There are two objects of the same type, called A and B respectively, so how do we distinguish who calls this method when calling method F ()?
For example:
class Banana {
void f(int i){
/***方法主体*****/
}
}
Banana a = new Banana();//生成Banana的对象a
Banana b= new Banana();//生成Banana的对象b
a.f(1);
b.f(2);
So how does the compiler know which object you are going to call the F () function? In fact, the transmission 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 invoked, a handle to this object is generated at the same time.
This is this is this point to object New Banana () or this is equivalent to the handle a;this "= =" A;
When we are in the interior of a method. And would like to get the handle of the current object, because this handle is secretly passed by the compiler, so there is no clear identifier to identify, this time we can use this keyword
The popular meaning of this: either the generated object invokes this method, and a pointer to the object is generated.
Classic example of 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().print();
}
}
1, to generate an object of the handle x syntax format for the Leaf x;
2. Create a leaf class object; The syntax format is the new Leaf ();
3. Establish the connection between the handle and the object; The syntax is x = new Leaf ();
4, call the object new Leaf () inside the method increment (); syntax is x.increment ()
XXX who called the method increment ()? is the object X (or the new leaf) of the leaf, so the corresponding system generates a this reference and points it secretly to X or to the object of the New Leaf (), so increment () returns a reference to X! is a memory address, we can print it out to see, we know!