For the readability of the program, it is common to name a variable representing the same property in a class, but doing so would cause the member variable to be inaccessible to the local variable name, and in order to solve the problem, Java introduced this keyword! So this function is used to access the other members of the object in the Method!
There are three common uses of the This keyword:
1) Through the This keyword can be explicit access to member variables, solve the same name with local variables contradiction! (When a member variable conflicts with a local variable)
Class student{ int id; public Student (int id) { this.id=id; } public int getId () { return this.id; }}
The parameter in the constructor method is the ID, which is a local variable with the same name as the member variable ID. You typically use This.id to access member variables in the constructor method, and you access the internal variables in the constructor method by ID!
2) The member method can be called through the This keyword! (When multiple member methods are used)
Class person{public void eat{... } public void behavior{ this.eat (); ... }}
When there are multiple member methods in a class, it is convenient to use the This keyword to invoke another member method in a member Method!
3) The constructor method is automatically called by the Java Virtual machine when instantiating the object, and cannot be called as a general member method in the program, but can be used by using this in a constructor method (parameter 1, parameter 2, Parameter 3 ...). ) in the form of a call to other constructor methods! (When multiple constructor methods are used)
Class student{public Student () { System.out.print ("Access parameterless constructor Method! "); } Public Student (String ID) {this (); SYSTEM.OUT.PRINTLN ("Access to the method of the parameter construction! "); }} public class eg{public static void Main (string[] args) { Student s=new Student (3);//When instantiating an object } }
But there are a few things to be aware of when using a third:
The call to <1> this () must be placed on the first line and only once!
The call to <2>this () can only be called in a constructor method, and no constructor method can be called in a member Method!
<3> cannot use this in two constructor methods of a class to call each other! It's easy to cause a dead loop!
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Java basics the This keyword!