CodeGym /Java Blog /Keywords in Java /Java this keyword
Author
Jesse Haniel
Lead Software Architect at Tribunal de Justiça da Paraíba

Java this keyword

Published in the Keywords in Java group
On CodeGym, students are introduced to the Java this keyword literally from the first lessons. Over time, its meaning becomes clear. But looking back, many people probably admit to themselves that for a long time they couldn't understand the Zen of this keyword. This article will pull back the curtain covering the secrets of the this keyword for anyone who has not yet been able to do so... I've you've got Schildt's Java reference, then on page 171 you can see that the this keyword is required for a method to reference the object that called it. We could end the lesson with that. But we need specifics. As a rule, you need to use this in two cases:
  1. When an instance variable and method/constructor variable have the same name;
  2. When you need to call a specific type of constructor (for example, a default constructor or parameterized constructor) from another type of constructor. This is also called an explicit constructor call.
And that's about it — there are just two cases where this fearful keyword is used. Now let's look at these two cases in examples.

Example 1: An instance variable and method variable have the same name.

Suppose we have a Human class that defines a name field: Let's create a setter for the name variable (the setter is fully functional — there's no catch here):

class Human {
    String name;


    public void setName(String newName) {
        name = newName;
    }
}
Note that we pass String newName to the setName setter method We declared a new variable and could have named it whatever we want because it will be visible only within the curly braces ({}) that enclose the setName method. Note that the setter has a single line:

name = newName;
Here we've introduced a new variable called newName and assigned it to the object's existing name variable. Many programmers might find it odd to introduce a variable with a new name when ultimately we are talking about the same thing. That is, we're talking about the name field in the Human class. That's why Java's creators thought up a way to conveniently use the same variable name. In other words, why have two names for a variable denoting the same thing. In other words, we want to do something like this:

class Human {
    String name;


    public void setName(String name) {
        name = name;
    }
}
But here we encounter a problem. We now have two variables with the same name. One String name belongs to the Human class, while the other String name belongs to its setName method. As a result, the JVM wouldn't know which variable you're referring to when you write the following line in the setter:

name = name;
Java assumes you mean the closest name variable, i.e. the one from the setName method: The this keyword (with examples) - 3So it turns out that you're simply assigning the method's name variable to itself. Which of course doesn't make any sense. Therefore, the language needed some way to distinguish the Human class's name variable from the name variable in the setName method. This problem was solved by introducing the this keyword, which in this case indicates that you intend to reference the variable associated with an instancen of the Human class, not the variable in the method: The this keyword (with examples) - 4In other words, this refers to the calling object, as we mentioned at the beginning of the article. As a result, the setName method sets the person's name on the created object. Below is the program's code without using the this keyword. The code creates a Human object and assigns a name to it: The this keyword (with examples) - 5And here is the code with the this keyword:

public class Solution {
    public static void main(String[] args) {
        Human human1 = new Human();
        human1.setName("Vinny");
        human1.print();
    }
}
class Human {
    String name;
    public String getName() {
        return name;
    }
    public void setName(String name){
        this.name = name;
    }
    void print() {
        System.out.println(name);
    }
}
Thus, this lets us avoid introducing new variables to denote the same thing, making the code cleaner and less cluttered with extra variables.

Example 2: Using this for an explicit constructor call

Calling one constructor from another can be useful when you have (oddly enough) multiple constructors and you don't want to the new constructor to duplicate initialization code previously written in a different constructor. Confused? It's not so scary as it seems. Look at the code below. It has two constructors for the Human class:

class Human {
    int age;
    int weight;
    int height;

    Human(int age, int weight) {
        this.age = age;
        this.weight = weight;
    }
    Human(int age, int weight, int height) {
        // Call the constructor with two parameters
        this(age, weight);
        // and then initialize the missing variable
        this.height = height;
    }
}
Here we have first provided a constructor with two parameters: int age and int weight. Suppose it has two lines of code:

this.age = age;
this.weight = weight;
Later we decide to add another constructor with three parameters, adding height to the existing age and weight parameters. You could write the new constructor like this:

this.age = age;
this.weight = weight;
this.height = height;
But instead of repeating existing code in this constructor, you can use the this keyword to explicitly call the constructor with two parameters:

this(age, weight);
// and then initialize the missing variable:
this.height = height;
It's as if we're saying to the three-parameter constructor:
  • call this other constructor that has two parameters
  • and then add another variable.
That's all =). Finally, we note that in Java the this keyword is used only in methods and constructors. But this is passed implicitly to all non-static methods (that's why this is often called an implicit parameter) and can be used to refer to the object that called the method. Don't be afraid of this keyword, because this is not scary.
Comments (2)
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION
MJS Level 3, Dublin, Ireland
5 March 2024
so perfect article thank you sir
Hoist Level 32, San Diego, United States
28 October 2021
The best _this_ article with graphics ! Code Gym does an excellent job of explaining vague mystical Java language topics (like the _this_ keyword) very thoroughly over time. You have to be patient since they get explained different ways at different times! Improved my understanding of Javascript too.