The this keyword in Java refers to the current object instance. It is used to access member variables and methods, call other constructors from the constructor, return the current object reference, and other occasions.
The role of this keyword in Java
In Java, the this keyword is a reference that points to The current object instance. It is mainly used for the following purposes:
Access the member variables and methods of the current object:
Example:
<code class="java">class Student { private String name; private int age; public Student(String name, int age) { this.name = name; this.age = age; } public String getName() { return this.name; } }</code>
Call other constructors from the constructor:
Example:
<code class="java">class Employee { private String name; private int salary; public Employee(String name) { this(name, 0); } public Employee(String name, int salary) { this.name = name; this.salary = salary; } }</code>
Returns the current object reference:
Example:
<code class="java">class StringBuilder { private String str; public StringBuilder append(String s) { str += s; return this; // 返回当前 StringBuilder 对象引用 } }</code>
Other uses:
The above is the detailed content of The role of this keyword in java. For more information, please follow other related articles on the PHP Chinese website!