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. Example: class container
{
Component comp;
Public void addcomponent ()
{
Comp = new component (this );
}
}
Class component
{
Container mycontainer;
Public component (container C)
{
Mycontainer = C;
}
} 3. The constructor is automatically called by the java system when an object is generated. ProgramTo call the constructor 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. 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;
}
}
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.
A Free Trial That Lets You Build Big!
Start building with 50+ products and up to 12 months usage for Elastic Compute Service