(reprinted) A summary of the usage of the in-depth Java keyword this

Source: Internet
Author: User

The meaning of it is not exactly the same, the improper use of the error will also occur,

In this paper, several usages and problems of this article are analyzed in detail.

Keywords: class; object; this; member variable; method; Construction method

, the Java language provides rich classes (class), interfaces (Interface), and corresponding methods (method).

Using these classes or interfaces, users can define
Their own classes or subclasses, and create objects (object) as templates for these classes.

In the Java language, when an object is created, the Java Virtual machine assigns it a pointer to the object itself, which is the "this". The keyword this is closely related to the object
The use of this in Java programming, it is difficult for many of us to understand it, because its syntax is more flexible, and what is the purpose of this one? Under what circumstances should it be used? This article is specific to analyze the use of this method.

First, use this to call member variables (attributes) in this class

Example 1: Look at the code below to see what's going on?

Class student{private String name;//define a member variable namepublic void SetName (String name) {//Set name, define a formal parameter namename=name; Pass the value of the local variable to the member variable}public String getName () {//Get 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 ()); }}

Run Result: Name: null

It can be seen from the running result that the content is not correctly assigned to the attribute through Name=name. Because the name of the operation at this point is actually a method, it is completely detached from the attributes in the class.

In addition, in this program code, there is a member variable name, and in the method there is a formal parameter, the parameter name is also name. The value of the form parameter name is then passed to the member variable name in the method. Although we can see what this code means,
For the Java compiler, how does it determine which variable to use? Is the value of the formal parameter name passed to the member variable name, or the value of the member variable name is passed to the formal parameter name?

This keyword will play a role at this point,
Use this keyword to represent a member variable in a class, also called a property of a class. So at this point, to explicitly indicate which one is the attribute in the class, add the "this. Property name" operation,

The code for the student class is improved as follows:

Class student{private String name;public void SetName (String name) {http://www.wenkuxiazai.com=name;//The value of the parameter is passed to the member variable}pu Blic String GetName () {return name: "+name;}}

In this case, the member variable in the class is represented, and the name to the right of the assignment number is the form parameter of the method, and the code name is the shape

The value of the parameter is passed to the member variable.

Example 1 only takes a formal parameter as an example. In fact, if it is a local variable, it is the same reason. A variable defined in a method body is called a local variable, and a variable defined outside the inner method body of a class is called a member variable. If the member variables and local changes in the method
The name of the volume is the same, then the member variable in the method is masked. If you want to use member variables at this time, you will need to use the keyword this. Use this to refer to the method format for member variables: this. member variable name.

Since this is capable of invoking member variables in this class, this can also invoke the member methods in this class. In Example 2, the program code is as follows:

Class student{private string Name;public void SetName (String name) {this.print ();//Call the Print method in this class}public string GetName ( {return "name:" +name;} public void print () {System.out.println ("Settings related information is as follows ...");}} public class thisexample02{public static void Main (String args[]) {Student stu=new Student (); Stu.setname ("Li Ming"); System.out.println (Stu.getname ()); }}

Operation Result:

Settings related information is as follows ... Li ming

In general, referencing member variables or member methods in the Java language is the object name. A member variable or an object name. The form of a member method. However, some programmers prefer to use this as a member variable, even when they do not have the same variable.
。 This is primarily from reading considerations that facilitate code. As soon as you see this keyword, you know that the variable you are referencing is either a member variable or a member method, not a local variable. This virtually improves the readability of the code.

Second, use this to call the constructor method

In a Java class, the constructor is a method with the same name as the class and must be the same as the class. And there must be a construction method in the Java class. If the constructor is not shown in the code, then the compiler will automatically add it at compile time.
A construction method with no formal parameters. There can be more than one construction method in a class that uses the same name, except for the formal parameter. The Java language depends on the user's parameters to determine which construction method to invoke. When there is more than one structure in a class
You can use the This keyword to call each other when creating a method. Suppose, there is now more than one constructor in a class, but no matter how many construction methods, as long as the object is instantiated, you must print a "new object instantiation" of the information, you can have
Two approaches.

The first approach: complete in the most primitive way, with the following code:

Class Student

Other methods, like constructor methods, call the constructor by formal arguments.

Method. The Java compiler determines which construction method to call, depending on the number of arguments passed.

Therefore, we sometimes need to call the other constructor in a constructor when we are actually programming. However, when other constructor methods are called using the This keyword, the This () call constructor method can only be placed on the first line of the constructor method, in order to
is sufficient to initialize the properties in the class, and at least one constructor is not called with this, or the program will get an error.

Class Student{private String name; private int age; public Student () {This ("Li Ming", 20);//Call the construction method with two arguments System.out.println ( "New Object Instantiation"); Public Student (String name) {this ();} Public Student (String Name,int ages) {this (name); this.age = ages;} public String GetInfo () {return ' name: ' + name + ', Age: "+ Age;}} public class thisexample05{public static void Main (String args[]) {Student stu1 = new Student ("Ted", 19); System.out.println (Stu1.getinfo ()); A recursive call was made to the construction method at this time, and the program error occurred.

Note that using the this call construction method only applies to the call of the constructed method, and other methods in the class cannot use this method.

Third, use this to refer to the current object

The most important particular is the current object, what is the current object? The current object in Java refers to the object that is currently invoking a method in the class. Referencing the current object using this refers to the need to return an object in the method of the class, and the object is
The current object of the class where the method resides, 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); Direct printing Thisreturn null; To ensure proper syntax, return null}}public class thisexample06{public static void Main (String args[]) {Student stu1 = new Student ();//Call Constructs an instantiated object Student STU2 = new Student ();//Call constructs an instantiated object System.out.println ("Main Method--" +stu1); Direct Print Object Stu1.getinfo (); The object that is currently calling the GetInfo () method is Stu1System.out.println ("Main Method-and" +STU2); Direct Print Object {private String name//name private int age;//Old public Student () {//no parameter constructed System.out.println ("new Object Instantiation");} pub  Lic Student (String name) {System.out.println ("new Object Instantiation");  The public Student (String name,int Age)//is assigned the value {System.out.println ("new Object Instantiation")//through the constructor method; Assigns a value to the Name property in the class This.age = age; Assign a value to the age property in a class} public String GetInfo () {//method of getting information return "Name:" + name + ", Age:" + Ages;}} public class thisexample03{public static void Main (String args[]) {Student stu1 = new Student ("Li Ming", 20);//Call construct instantiation Object Sys Tem.out.println (Stu1.getinfo ()); Get information}} 

In this example, a parameterless construction method, a constructor that provides a parameter for setting the name, and a construction method that provides two parameters for setting the name and age, all three methods are used to print the information instantiated by the new object, and it is clear that this
If it is not appropriate to write an output statement in each of the construction methods, some of the code is repeated, and now it is just a line, so it does not feel, if the code has a lot of lines now, the above code defects immediately appeared. Well, it's best to let
Constructs the method to make the mutual invocation, then can use "this (parameter list)" The form completes, uses this to modify above code as follows:

Class student{Private String name, private int age, public Student () {System.out.println ("new Object Instantiation");} Public Student (string name) {this ();//calls the parameterless construction method in this class http://www.wenkuxiazai.com = name;} public Student (String name,i NT age) {this (name);//Call a constructor method with a parameter This.age = age;} Public String GetInfo () {//method of getting information return "Name:" + name + ", Age:" + Ages;}} public class thisexample04{public static void Main (String args[]) {Student stu1 = new Student ("Li Ming", 20); System.out.println (Stu1.getinfo ()); }}

There are multiple constructors in a class, because the names are the same, and the class names are the same, so what is the constructor method called?

Stu2.getinfo (); The GetInfo () method is currently called

}}

Let's use an example to explain this reference to the current object. public class Car

{public Car Getcarobject () {return this;//return current Object}

public static void Main (string[] args) {Car sc = new car ();//Create a Car object System.out.println (Sc.getcarobject () instanceof Car);

}}

This defines a method Getcarobject () that returns a type of car, and uses the This keyword to return the current object car. Create a Car object in the main () method and use the Instanceof method to determine the object returned by the Getcarobject () method with car
Whether the object matches. The run result is true.

Iv. Other uses

In addition to the above, this can also be used in other situations. For example, a comparison of objects, you can use this and a reference to pass two to determine whether the object is equal. For example, a student class is as follows:

Class student{private string name, private int age, public Student (String Name,int age) {this.setname (name); this.se Tage (age); public void SetName (String name) {//Set name} public void Setage (int ages) {//set age this.age = aged;} public String GetName ( ) {return;} public int getage () {return this.age;}}

Generates two objects, and when the names and ages in two objects are exactly equal, the objects are considered equal, but at this point there are two problems: How to compare objects? Second, where to compare? In this example, the name is defined as a string type,
We know that the string itself is a class, and if you want to make an equal comparison, you must use the Equals () method to determine whether the content is equal. When age is defined as Integer, it can be done directly using "= =". In addition, objects should be compared by themselves.
Row comparison is most appropriate, so you should add a comparison method to the student class, with the following code:

Class student{private string name, private int age, public Student (String Name,int age) {this.setname (name); This.set Age (age); }public Boolean compare (Student stu) {//Call this method when there are two objects in it: The current object, the incoming object Student S1 = this;//The current object represents stu1student s2 = stu;//Pass In the object, it means Stu2if (S1==S2) {//judgment is not the same object, using the address to compare return true;}//After each property is judged equal if (equals () &&s1.age==s2.age) { return true; Two objects equal}else{return false;//two objects unequal}}public void SetName (String name) {//Set name  ;} public void Setage (int ages) {//Set 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);//Declaration two objects, content exactly equal Student STU2 = new Student ("Li Ming", 20); Declares two objects, the content is exactly equal//directly in the main method to get the individual properties to compare if (Stu1.compare (STU2)) {System.out.println ("two objects equal!"). ") ;} else{System.out.println ("Two objects are not equal! ") ;} }}

The addresses are equal, two objects are equal, and if the addresses are not equal, the contents of each attribute are judged to determine whether they are equal.

Conclusion: This in Java is closely related to object-oriented programming, which represents the current object.

However, the real meaning that it represents is not exactly the same in different use cases. this. member variable, this. member method (parameter list): actually all indicate when
A property in the previous object or a method that is called by the current object; The core of this represents the current object, the object that is currently manipulating this method is called the current object, and this can be used to call other constructor methods, but this statement must be placed in the first row of the constructor method

The use of this plays an important role in saving code, distinguishing between local variables and member variables, and comparing objects, and we should give attention to programming and learn to use it correctly.

(reprinted) A summary of the usage of the in-depth Java keyword this

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.