Three situations where the this keyword must be used: 1. We want to assign the externally passed parameters to the member variables of the class through the constructor, the constructor's form parameter name is the same as the member variable name of the class. Example: class person
...{
String name;
Public Person (string name)
...{
This. Name = Name;
}
}
2. Assume that there is a container class and a component class. In a method of the container class, you must create an instance object for the component class, the component class constructor must accept a parameter representing its container. For example:
Class container
...{
Component comp;
Public void addcomponent ()
...{
Comp = new component (this );
}
}
Class component
...{
Container mycontainer;
Public component (container C)
...{
Mycontainer = C;
}
}
3. constructor is automatically called by the java system when an object is generated. We can no longer call constructor in the program like calling other methods. However, we can call other overloaded constructor methods in a constructor, instead of using the constructor name, but in the form of this (parameter list). Based on the parameter list, select the corresponding constructor. For example
Public class person
...{
String name;
Int age;
Public Person (string name)
...{
This. Name = Name;
}
Public Person (string name, int age)
...{
This (name );
This. Age = age;
}
}
1. This can refer to the object itself: When you need to explicitly specify the object's own attributes or methods in a class, you should add this reference, as shown in the following example:
The output result is maybe = love you.
This. Maybe = love
This. Maybe = love you
The first line directly outputs the parameter maybe passed in the constructor, the second line is the output of the member variable (attribute) Maybe, and the third line is the first for the member variable (attribute) maybe is assigned a value before output.
2. When a constructor calls another constructor, use the keyword "this:
Example:
Public class flower ...{
Private int petalcount = 0;
Private string S = new string ("null ");
Public flower (INT petals )...{
Petalcount = petals;
}
Public flower (string SS )...{
S = SS;
}
Public flower (string S, int petals )...{
This (petals); // in Java, another constructor can be called once, and this statement must be in the first line of the constructor.
This. S = s;
}
}
Public class love ...{
String maybe = "love ";
Public love (string maybe )...{
System. Out. println ("Maybe =" + maybe );
System. Out. println ("this. Maybe =" + this. Maybe );
This. Maybe = maybe;
System. Out. println ("this. Maybe =" + this. Maybe );
}
Public static void main (string [] ARGs )...{
Love S = new love ("love you ");
}
}
Thank you: http://lw223.javaeye.com/blog/211442
Learning