The "this" keyword

Hey y’all,

I feel like I only have a very loose grasp on use of the “this” keyword. I’ve been googling and trying to find an explanation that makes sense and am not having much luck, so I am checking with the community here.

How did you learn about using “this” that made it make sense to you?

1 Like

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 names 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!

1 Like

To take this a step further.

In C++, the this is actually a pointer (that is, an address to the object in memory) which can be passed around when necessary. For example, if you need to let an enemy know that you’re it’s target you can call a theoretical SetTarget(Player* player) function like this: SetTarget(this)

Which is to say, you can also use this as an argument to pass into functions!

1 Like

This topic was automatically closed 20 days after the last reply. New replies are no longer allowed.

Privacy & Terms