In-depth Summary of the usage of the Java keyword "this" and the usage of the java keyword "this"

Source: Internet
Author: User

In-depth Summary of the usage of the Java keyword "this" and the usage of the java keyword "this"

This is often seen in Java programming, which makes program design standardized, simple, and flexible. However

The meaning is not exactly the same. improper use may lead to errors,

This article analyzes several usage and problems of this.

Key words: Class; object; this; member variable; method; Constructor

Java provides a wide range of classes, interfaces, and methods ).

You can use these classes or interfaces to define
Class or subclass, and use these classes as templates to create objects ).

In Java, after an object is created, the Java Virtual Machine assigns a pointer to the object itself, which is "this ". This keyword is closely related to the object
This is often used in Java programming. It is hard for many of us to understand it. Because of its flexible syntax, what is the use of this? Under what circumstances should I use it? This article analyzes how to use this.

1. Use this to call the member variables (attributes) in this class)

Example 1: Observe the following program code to see what problems will occur?

Class Student {private String name; // defines a member variable namepublic void setName (String name) {// sets the name and defines a parameter namename = name; // pass the local variable value to the member variable} public String getName () {// get the name return "name:" + name ;}} public class ThisExample01 {public static void main (String args []) {Student stu = new Student (); stu. setName ("Li Ming"); System. out. println (stu. getName ());}}

Running result: Name: null

The running result shows that the content is not correctly assigned to the attribute through name = name. Why? In this case, the name of the operation is actually in the method and is completely irrelevant to the attributes in the class.

In addition, there is a member variable name in this program code, and there is a form parameter in the method, the parameter name is also name. Then, pass the value of the formal parameter name to the member variable name in the method. Although we can understand the meaning of this code
How does a Java compiler determine which variable to use? Is the value of the formal parameter name passed to the member variable name, or is the value of the member variable name passed to the formal parameter name in turn?

This keyword plays a role.
The keyword "this" is used to represent the member variables in the class, also known as the attributes of the class. Therefore, to explicitly indicate which attribute is in the class, the "this. attribute name" operation must be added,

Improve the code of the student class as follows:

Class Student {private String name; public void setName (String name) {http://www.wenkuxiazai.com = name; // pass the value of the parameter to the member variable} public String getName () {return "name:" + name ;}}

 

At this time, it indicates the member variable in the class, and the name on the right of the value assignment number is a form parameter of the method, and the code name is the form

Parameter value is passed to the member variable.

Example 1 is just a form parameter. In fact, if it is a local variable, it is the same principle. The variables defined in the method body are called local variables, and the variables defined externally in the internal method body of the class are called member variables. If the member variables and methods are partially changed
If the value is the same, the member variables in the method will be blocked. If you want to use a member variable at this time, you need to use the keyword "this. The format of using this to reference member variables: this. member variable name.

Since this can call member variables in this class, this can also call Member methods in this class. Take example 2 as an example. The program code is as follows:

Class Student {private String name; public void setName (String name) {this. print (); // call the print method} public String getName () {return "name:" + name;} public void print () {System. out. println ("the settings are as follows ...... ") ;}} Public class ThisExample02 {public static void main (String args []) {Student stu = new Student (); stu. setName ("Li Ming"); System. out. println (stu. getName ());}}

Running result:

The settings are as follows ...... Li Ming

Generally, the reference to member variables or member methods in Java are in the form of Object Name, member variable, or object name. Member method. However, some programmers prefer to reference variables in the form of this. member variables even if they do not have the same variables.
. This is mainly from the convenience of reading the code. Once you see this keyword, you will know that the currently referenced variable is a member variable or a member method, rather than a local variable. This virtually improves the readability of the Code.

Ii. Use this to call the constructor

In a Java class, the constructor is a method with the same name as the class and must be the same as the class name. In addition, a constructor must exist in the Java class. If the constructor is not displayed in the Code, the compiler automatically adds
A constructor without formal parameters. Multiple constructor methods can exist in a class. These constructor methods use the same name, but the formal parameters are different. The Java language uses USER Parameters to determine which constructor to call. When a class has multiple structures
You can use this keyword to call each other during method creation. Assume that there are multiple constructor methods in a class, but no matter how many constructor methods there are, as long as the object is instantiated, you must print the information of "New Object Instantiation ".
Two methods.

First, follow the original method. The specific code is as follows:

Class Student

Similar to other methods, constructor is called through formal parameters.

Method. The Java compiler determines which constructor to call based on the number of passed parameters.

Therefore, in actual programming, we sometimes need to call another constructor in one constructor. However, when you use the this keyword to call other constructor methods, this () call constructor can only be placed in the first line of the constructor, In order
It is enough to initialize the attributes in the class, and at least one constructor does not need this call. Otherwise, the program will have an error.

Class Student {private String name; private int age; public Student () {this ("Li Ming", 20); // call the construction method System with two parameters. out. println ("New Object Instantiation");} public Student (String name) {this ();} public Student (String name, int age) {this (name); this. age = age;} public String getInfo () {return "name:" + name + ", age:" + age ;}} public class ThisExample05 {public static void main (String args []) {Student stu1 = new Stud Ent ("Li Xiaoming", 19); System. out. println (stu1.getInfo () ;}} at this time, the constructor calls the method recursively and the program fails.

 

Note that using this to call the constructor is only applicable to calling the constructor method. Other methods in the class cannot use this method.

3. Use this to reference the current object

This indicates the current object. What is the current object? In Java, the current object is the object that is currently calling methods in the class. Using this to reference the current object means that if an object needs to be returned in the class method, and the object is
The current object of the class where the method is located. You can use the this keyword as the return value of the method. For example:

Class Student {public String getInfo () // method for obtaining information {System. out. println ("Student Class -->" + this); // print thisreturn null directly; // to ensure correct syntax, return null} public class ThisExample06 {public static void main (String args []) {Student stu1 = new Student (); // call to construct the instantiated object Student stu2 = new Student (); // call to construct the instantiated object System. out. println ("MAIN method -->" + stu1); // print the stu1.getInfo () object directly; // The object currently calling the getInfo () method is stu1System. out. println ("MAIN method -->" + stu2); // directly print the object {private String name // name private int age; // age public Student () {// The System is constructed without parameters. out. println ("New Object Instantiation");} public Student (String name) {System. out. println ("New Object Instantiation");} public Student (String name, int age) // assign a value to {System. out. println ("New Object Instantiation"); // assign this to the name attribute in the class. age = age; // assign a value to the age attribute in the class} public String getInfo () {// return "name:" + name + ", age: "+ age ;}} public class ThisExample03 {public static void main (String args []) {Student stu1 = new Student (" Li Ming ", 20 ); // call to construct the instantiated object System. out. println (stu1.getInfo (); // obtain information }}

 

In this example, a construction method without parameters, a construction method that provides a parameter to set the name, and a construction method that provides two parameters to set the name and age, these three methods are used to print the information of New Object Instantiation. Obviously, this
If the output statement is written in each constructor, it is definitely not suitable. Some of the Code is repeated, and now it is only one line, so I cannot feel it, if the current Code has many lines, the defects of the above Code will immediately become apparent. So, it is best to make
The constructor calls each other. Then, you can use the "this (parameter list)" form to modify the Code as follows:

Class Student {private String name; private int age; public Student () {System. out. println ("New Object Instantiation");} public Student (String name) {this (); // call the non-argument constructor http://www.wenkuxiazai.com in this class = name ;} public Student (String name, int age) {this (name); // call the constructor of a parameter this. age = age;} public String getInfo () {// method for obtaining information return "name:" + name + ", age:" + age ;}} public class ThisExample04 {public static void main (String args []) {Student stu1 = new Student ("Li Ming", 20); System. out. println (stu1.getInfo ());}}

A class has multiple constructor methods. Because the names are the same and the class names are the same, which constructor does this call?

Stu2.getInfo (); // The getInfo () method is currently called.

}}

Let's use another example to explain how this references the current object. Public class Car

{Public Car getCarObject () {return this; // returns the current object}

Public static void main (String [] args) {Car SC = new Car (); // create a Car object System. out. println (SC. getCarObject () instanceof Car );

}}

GetCarObject () is defined here, and the current object Car is returned using the this keyword. Create a Car object in the main () method and use the instanceof method to determine whether the objects returned by the getCarObject () method and the Car
Whether the object matches. The running result is true.

IV. Other usage

In addition to the above cases, this can also be used in other scenarios. For example, for object comparison, you can use this and reference transmission to determine whether two objects are equal. For example, a student is as follows:

Class Student {private String name; private int age; public Student (String name, int age) {this. setName (name); this. setAge (age);} public void setName (String name) {// set name} public void setAge (int age) {// set the age this. age = age;} public String getName () {return;} public int getAge () {return this. age ;}}

Two objects are generated. When the names and ages of the two objects are completely equal, the objects are considered equal. However, two problems arise at this time: first, how to compare objects? Second, where can we compare them? In this example, the name is defined as String type,
We know that the String itself is a class. If you want to perform an equal comparison, you must use the equals () method to determine whether the content is equal. The age is defined as an integer and can be directly completed using "=. In addition, the object should be compared by yourself.
The row is the most suitable, so you should add a comparison method in the Student class. The specific code is as follows:

Class Student {private String name; private int age; public Student (String name, int age) {this. setName (name); this. setAge (age);} public boolean compare (Student stu) {// when this method is called, two objects exist: the current object and the passed object Student s1 = this; // The current object indicates stu1Student s2 = stu; // The passed object indicates stu2if (s1 = s2) {// determine whether it is the same object, compare return true with the address;} // then determine whether each attribute is equal if (equals () & s1.age = s2.age) {return true; // two objects are equal} else {return fal Se; // two objects are not equal} public void setName (String name) {// Set name;} public void setAge (int age) {// set age this. age = age;} public String getName () {return;} public int getAge () {return this. age ;}} public class ThisExample07 {public static void main (String args []) {Student stu1 = new Student ("Li Ming", 20); // declare two objects, the content is completely equal. Student stu2 = new Student ("Li Ming", 20); // declare two objects, and the content is completely equal. // compare each attribute directly in the main method if (stu1.c Ompare (stu2) {System. out. println ("the two objects are equal! ");} Else {System. out. println (" two objects are not equal! ");}}}

If the addresses are equal, the two objects are equal. If the addresses are not equal, the content of each attribute is determined in order to determine whether they are equal.

Conclusion: this in Java is closely related to object-oriented programming, and it represents the current object.

However, in different usage scenarios, the true meaning is different. This. member variable, this. Member method (parameter list): Actually all indicate when
Attribute in the previous object or method called by the current object; the core of this indicates the current object, and the object currently operating this method is called the current object; other constructor methods can be called using this, however, this statement must be placed in the first line of the constructor.

This plays an important role in saving code, distinguishing local variables from member variables, and comparing objects. During programming, we should pay attention to it and learn to use it correctly.

Related Article

Contact Us

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

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.