JavaRush /Java Blog /Random EN /keyword this {in examples}
Author
Jesse Haniel
Главный архитектор программного обеспечения at Tribunal de Justiça da Paraíba

keyword this {in examples}

Published in the Random EN group
At JavaRush, students are introduced to the keyword literally from the first lectures this. And over time it becomes clear what it means. But many, looking back, will probably honestly say to themselves that for a long time they could not realize the zen of this key word. In this article we lift the veil of secrets about using keywords thisfor those who still can’t figure it out... Welcome! If you pick up Schildt's Java reference book , on page 171 you'll read that a keyword thisis required so that a method can reference the object that called it. This could actually be the end of it. But we need specifics. Keyword this {in examples} - 1As a rule, thisit should be used in two cases:
  1. When a class instance variable and a method/constructor variable have the same name;
  2. When you need to call a constructor of one type (for example, a default or parameterized constructor) from another. This is also called an explicit constructor call.
That's it, not much really, just two instances where this dreaded keyword is used. Now let's look at these two situations with examples.

Example one - instance variable and method variable have the same name

Let's say we have a class Humanfor which the "name" field is defined: Keyword this {in examples} - 2Let's namecreate a setter for the variable (the setter is quite working and there is no trick here): Please note that we are passing the variable Keyword this {in examples} - 3to the method (setter) . We introduced a new variable and (in general) could call it whatever we wanted because it would only be visible within the {curly braces} of the method . Notice that there is one line in the setter: setNameString newNamesetName
name = newName;
That is, in fact, we introduced a new variable newNameand assigned it to a variable already existing in the class name. Many programmers thought it strange to introduce a variable with a new name if in the end we are talking about the same thing. About the name in the class Human. Therefore, the language developers thought about making it convenient to use one variable name. In other words, why have two names for a variable that means the same thing. That is, I would like to do something like this: Keyword this {in examples} - 4But in this case a problem arises . We now have two variables that are named the same. One String namebelongs to the class Human, and the other String nameto its method setName. Therefore, the Java machine does not know which variable you mean when you write a string in a setter:
name = name;
Java takes the closest one - namefrom the method setName:
Keyword this {in examples} - 5
and it turns out that you simply assign a value to a variable namefrom this method, to it. Which of course doesn't make any sense. Therefore, some way was needed to distinguish a variable namefrom a class Humanfrom a variable namefrom a method setName. To solve this problem, the keyword was introduced this, which in this case will indicate that it is necessary to call a variable not of a method, but of a class Human:
Keyword this {in examples} - 6
That is, thisit will refer to the calling object, as was said at the beginning of the article. As a result, the name of the person setNamewill be set through the setter to the created object. Below is the code without using the keyword this. The code creates a class object Humanand gives it a name:
Keyword this {in examples} - 7
And below is the program code with the keyword this:
public class Solution{
    public static void main(String[] args) {
        Human human1 = new Human();
        human1.setName("Volodya");
        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, it thisavoids introducing new variables to denote the same thing, which makes the code less “overloaded” with additional variables.

Example Two - Using this to explicitly call a constructor

Calling one constructor from another can be useful when you (oddly enough) have several constructors and you do not want to rewrite the initialization code given earlier in the constructor in a new constructor. Confused? Everything is not as scary as it seems. Look at the code below, it has two class constructors Human:
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){
        //you call the constructor with two parameters
        this(age, weight);
        //and add the missing variable
        this.height = height;
    }
}
Here we first have a two-parameter constructor that accepts int ageand int weight. Let's say we wrote two lines of code in it:
this.age = age;
this.weight = weight;
and then they decided to add another constructor, with three parameters, which, in addition to age and weight, also takes height. In the new constructor you could write this:
this.age = age;
this.weight = weight;
this.height = height;
But instead of repeating the code you've already written in this constructor, you can use a keyword to thisexplicitly call the constructor with two parameters:
this(age, weight);
// and add the missing variable:
this.height = height;
So you're kind of telling the constructor with three parameters:
  • call this constructor, which has two parameters.
  • and add the missing variable.
That's all =). Finally, we note that the this keyword in Java is used only as part of methods or constructors of a class instance. But implicitly, the keyword thisis passed to all methods except static ones (hence why it thisis often called an implicit parameter) and can be used to refer to the object that called the method. There is no need to be afraid of this keyword, because Thisit is not scary.
Keyword this {in examples} - 9
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION