The this keyword in java must be placed in non-static methods. The this keyword represents itself. Its main uses in the program are as follows:
1 , Reference member variables;
2. Reference other construction methods within its own construction method;
3. Represent objects of its own class;
4. Reference member methods;
Let’s take a look at these four usages respectively:
1. Reference member variables
In a class method or constructor Internally, you can use the format "this. member variable name" to reference the member variable name. Sometimes it can be omitted, and sometimes it cannot be omitted.
Code example:
/** * 使用this引用成员变量 */ public class ReferenceVariable { private int a; public ReferenceVariable(int a){ this.a = a; } public int getA(){ return a; } public void setA(int a){ this.a = a; } }
(Video tutorial recommendation: java video tutorial)
2. Reference construction method
Within the constructor of a class, you can also use the this keyword to reference other constructors, which can reduce code duplication and keep all constructors unified, which facilitates future code modifications. and maintenance, and also facilitates code reading.
Code example:
/** * 使用this关键字引用构造方法 */ public class ReferenceConstructor { int a; public ReferenceConstructor(){ this(0); } public ReferenceConstructor(int a){ this.a = a; } }
3. Represent its own object
Inside a class, you can also use this to represent the object of its own class, or In other words, there is an implicit member variable inside each class. The type of the member variable is the type of the class. The name of the member variable is this. The sample code that actually uses this to represent the object of its own class is as follows:
/** * 使用this代表自身类的对象 */ public class ReferenceObject { ReferenceObject instance; public ReferenceObject(){ instance = this; } public void test(){ System.out.println(this); } }
4. Reference member methods
Within a class, you can also use "this.methodname(parameter) when calling each other between member methods )" to make a reference, but this can be omitted in all such references.
Recommended tutorial: java entry program
The above is the detailed content of What are the four uses of this keyword in java. For more information, please follow other related articles on the PHP Chinese website!