This
1. Returns a reference to the object that called the current method.
public class leaf{
private int i=0;
Public Leaf increament () {
i++;
return this;
}
public static void Main (string[] args) {
Leaf x= New Leaf ();
X.increment (). print ();
Leaf y= New Leaf ();
Y.increment (). print ();
}
}
This represents an instance of the leaf class when executing x.increment (), this represents a reference to instance X. Similarly executes y.increment (), which represents a reference to instance Y.
2. Call the other constructor methods of the current class in the constructor method.
Defines the construction method of the 3 person class, which is no parameter, has a parameter, has two parameters, implements the code reuse, uses this () and this (_name) to invoke person () and person (String _name)
When you use this to invoke other constructor methods, you must place them at the beginning of the construction method and no I will not compile
public class person{
private String name;
private int age;
Private String sex;
Public person () {
sex= "Male";
}
Public person (String _name) {
This ();
Name=_name;
}
Public person (String _name,int _age) {
This (_name);
Age=_age;
}
}
3. When the method parameter name and member variable name are the same, it is used to distinguish parameter names from member variables.
The parameter name of the setter method is the same as the member variable name, this.name represents the member variable name, and name indicates the parameter name.
public class person{
private String name;
privae int age;
public void SetName (String name) {
This.name=name;
}
public void Setage (int.) {
This.age=age;
}
}
Java basics Use of this 10.13