What is the meaning of "this" in Java?
In Java, the this
keyword refers to the current object. It is used to refer to the instance variables and methods of the current object from within the object's own methods.
Here is an example of how this
is used in Java:
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return this.name;
}
public int getAge() {
return this.age;
}
}
In this example, the this
keyword is used to refer to the instance variables name
and age
and the instance methods setName
, setAge
, getName
, and getAge
of the Person
object.
The this
keyword is also used to pass the current object as an argument to a method or constructor. For example:
public class Person {
// ...
public void printPerson() {
System.out.println(this);
}
public String toString() {
return "Person[name=" + name + ",age=" + age + "]";
}
}
In this example, the printPerson
method uses the this
keyword to pass the current Person
object to the toString
method, which returns a string representation of the object.
I hope this helps. Let me know if you have any questions.