1. This reference handle
This refers to the object that called the method
classa{String name; PublicA (String x) {name=x; } Public voidfunc1 () {System.out.println ("My name is" +name); } Public voidFunc2 () {A A2=NewA ("A2"); A2.func1 (); This. Func1 ();//This can be removed and the result is consistentfunc1 (); } Public Static voidmain (String [] args) {A A1=NewA ("A1"); A1.FUNC2 (); }}/*F:\java_example>java Amy name is a2my name was a1my name is A1*/
In the member method, the effect is the same as adding this reference to the members of the same class, which is like, we are members of the same company, when we mention the things related to our company, needless to say the company name, of course, we can also explicitly point out how our company, There is a this reference variable inside each member method, pointing to the object that called the method.
Seemingly this is optional, but in some cases it is very necessary
1) We assign the externally passed parameters to the class member variable by constructing the method, the parameter name of the constructor is the same as the member variable name of the class
Class Person
{
String name;
Public person (String name)
{
This.name=name;
}
}
2) can be passed as an object class Containe{
Class Container
{
Component comp;
public void AddComponent ()
{
comp = new Component (this);
/*comp = new Component (new Container ());
This is unreasonable, because what I want is to put the newly created part in the container object that calls the AddComponent ().
If I were to create a new container class now, that would put this part into the newly created container class,
In order to correspond to only one container class, we can use this to represent our object
*/
}
}
Class Component
{
Container Mycon;
Public Component (Container con)
{
Mycon=con;
}
}
3) The construction method is automatically called by the Java system when the object is generated, and we cannot invoke the constructor in the program like any other function. But we can call other overloaded constructors in a constructor method through this form.
Class person{string Name;int age;public person (String name) {this.name=name;} Public person (String Name,int age) {This (name); this.age=age;}}
Java Basics-Learning Note (vii)--this keywords