You can think of this
as meaning “this current object”. For example:
public class Player () {
private String name;
public String getName() {
return this.name; //This will return the name property belonging to this object..
}
}
The reason this can get confusing is that, in the above example, you could just return name;
:
public void getName() {
return name; //This does the same thing!
}
I use this
out of habit, and because I like to explicitly refer to the property I want to access. However, an advantage is that you can distinguish between two variables with the same name. For example, let’s code up a setter method:
public class Player () {
private String name;
public void setName(String name) {
}
We have two name
s now! One is the property name
, and the other is the parameter for setName()
! How can we distinguish between these? We can use this
:
public void setName(String name) {
this.name = name; //Set the property name to the value of the local variable name
}
Another way of thinking about this is to imagine how you call properties and methods on other objects. this
works exactly the same way, it is just referring to the current object. For example, we could add a method to transfer money from our player to another player:
public class Player () {
public int money = 1000;
private void tradeMoney(Player otherPlayer, int amount) {
this.money -= amount; //Subtract amount from our money
otherPlayer.money += amount; //Add the amount to the other player's money
}
}
Hope that helps!