In a method, you can use a keyword this to represent the object itself. In a normal method, this represents the object that called the method; in the constructor, this represents the newly created object
1. Use this to access the fields and methods of an object
For example: Use name in method SayHello and use THIS.name to be the same;
void SayHello () {
System.out.println ("hello! My name is "+name");
}
And
void SayHello () {
System.out.println ("hello! My name is "+this.name");
}
The meaning is the same.
2. Use this to resolve an issue where the local variable has the same name as the field
You can also use this to resolve problems with local variables (variables in methods) or parameter variables with the same name as field variables. For example, in the construction method, this is often used:
person (int age,string neme) {
This.age=age;
This.name=name;
}
Here, This.age represents a field variable, and age represents a parameter variable.
3. Construct method, call another method of construction with this
Such as:
Person () {
This (0, "");
}
If you call another constructor method in the constructor, the call statement must be placed in the first sentence. (more complex questions about the construction method)
4. Precautions for using this
When using this, be aware that this refers to the invocation of the "object" itself, not the variable or method seen in this class definition.
Attention:
(1) This can not only refer to the domains and methods defined in the class, but also to the domains and methods defined in the parent class of the class.
(2) because it refers to an object, this does not refer to the class variable (static field) through this, and the class method
In fact, in all non-static methods, a parameter this is implied. This is not available in the static method.
The use of my java--this