1.this refers to the current object itself.
You should add the this reference when you want to specify in a class the variables or functions that use the object itself. As in the following example:
publicclassa{
Strings= "Hello";
PublicA (Strings) {
System.out.println ("s=" +s);
System.out.println ("1->this.s=" +THIS.S);
This.s=s;
System.out.println ("2->this.s=" +THIS.S);
}
Publicstaticvoidmain (String[]args) {
Newa ("helloworld!");
}
}
Run Result:
s=helloworld!
1->this.s=hello
2->this.s=helloworld!
In this example, in constructor A, the argument s and the variable s of Class A have the same name, and if the S is operated directly, the parameter S is manipulated. To operate on the variable s of Class A, you should use this as a reference. The first line of the running result is to print the result directly on the parameter S, and the next two lines are the result of the operation before and after the variable s of object A.
2. Pass this as a parameter
You can also use this when you want to pass yourself as an argument to another object. Such as:
publicclassa{
PublicA () {
Newb (This). Print ();
}
Publicvoidprint () {
System.out.println ("hellofroma!");
}
}
publicclassb{
Aa;
PUBLICB (Aa) {
This.a=a;
}
Publicvoidprint () {
A.print ();
System.out.println ("hellofromb!");
}
}
Run Result:
hellofroma!
hellofromb!
In this example, in the constructor of object A, the object A is passed to the constructor of object B using Newb (this) as the parameter.
3. Note this in the anonymous class and in the inner class.
Sometimes we use some internal classes and anonymous classes. When this is used in an anonymous class, this refers to the anonymous class or the inner class itself. Then if we want to use the methods and variables of the outer class, we should add the class name of the outer class. As the following example:
publicclassa{
Inti=1;
PublicA () {
Threadthread=newthread () {
Publicvoidrun () {
for (;;) {
A.this.run ();
try{
Sleep (1000);
}catch (Interruptedexceptionie) {
}
}
}
};
Thread.Start ();
}
Publicvoidrun () {
System.out.println ("i=" +i);
i++;
}
Publicstaticvoidmain (String[]args) throwsexception{
Newa ();
}
}