The this
keyword in Java is a reference variable which points (or refers) to the current instance of a class. The keyword resolves any ambiguity between a parameter and member variable of the same name. Its uses are the following:
The this
keyword can be used to call functions and access member variables of the current instance. There are situations when the name of a variable, which is a member of a class, is the same as that of the parameter. In such a case, using the this
keyword is mandatory with the variable which is a member of the class; otherwise, the program won’t compile.
public void setName(String fName, String lName){
this.fName = fName;
this.setLastName(lName);
}
We can pass the current instance to another function using the this
keyword. It may be a constructor or a normal function:
class Person{
Animal pet;
Person(Animal a){
a = pet;
}
}
class Animal{
String colour;
String name;
Person owner;
public Animal(String colour){
this.colour = colour;
}
public Animal(String colour, String name){
this.colour = colour;
this.name = name;
// passing itself to the constructor
owner = new Person(this);
}
}
Free Resources