When do I really need to use the this operator in Java?

2

I sometimes think there is no need to use this , but since I just started learning Java, I want someone to answer when it really will be necessary to use the this operator?

    
asked by anonymous 21.09.2016 / 21:21

4 answers

5

4 situations:

  • Referencing an instance variable of the class unambiguously

    It is possible but it is usually recommended to avoid using where it is not ambiguous. So if an instance variable of the class does not conflict with a method variable or parameter name, it is common to avoid use. It is considered implicitly existing.

  • Use as argument of a method that will call when you want to pass the current object itself

    This is useful when you do not have a specific variable to pass as an argument, the intention is to pass the object itself, what is the name of the current object of the class? this . Below I explain why this is the variable.

  • Access an instance within an inner class:

    public class Externa {
        private int x;
        public class Interna {
            private int x;
            public int exemplo() {
                return Externa.this.x;
            }
        }
    }
    
  • Calling a constructor of the object itself

    There are problems with calling constructors inside constructors. This is a way of indicating that what you are calling is the constructor. There is a special treatment. This call must be the first line of the constructor, there may not be another code before. More in detail in What does this () do in the builder alone?

Note that the this in the first two cases work practically as a variable. What most people do not know is that the method is just a function like any other that has a hidden parameter called this . It's just a syntactic sugar. This variable can be used in a variety of ways. Then:

class Tipo {
    private int variavel;
    public void exemplo(int x) {
        variavel = x;
    }
}

In the background is this:

class Tipo {
    private int variavel;
    public void exemplo(Tipo this, int x) {
        this.variavel = x;
    }
}

And this is an example of the first use described. I speak in more detail in C # (it's the same thing).

The third form is very similar to this case.

The second form would be:

class Tipo {
    public void exemplo(Tipo this, int x) { //já escrito sem o açúcar sintático
        metodoDeOutraClasse(this, x); //passa o objeto atual e o parâmetro x
    }
}

Obviously, in this case the signature of the method would be something like metodoDeOutraClasse(Tipo objeto) . This method most likely belongs to another class, it would not make sense to it.

In the fourth case, this works especially in language. It uses this naming convention to indicate that it is calling a constructor.

class Tipo {
    public Tipo(int x) {
        System.out.println(x);
    }
    public Tipo() {
        this(1);
    }
}
    
21.09.2016 / 21:36
5

The only case in which you need to use this is when you have a scope variable (or parameter) with the same name as an attribute (or class variable) the.

A common example

public class Cliente {
    private String nome;

    public void setNome(String nome){
        this.nome = nome;

        //perceba que nome se refere ao parâmetro e this.nome se refere ao atributo
    }
}

Other than that, you will never be "forced" to use it. This is a subject of the style you each use to encode.

    
21.09.2016 / 21:28
2

Explaining in a less formal way, this refers to the current object. For example: you have a ball object with a color property, you can access the color property with this.cor

The this() method with or without parameters refers to the constructor of your class. This can only be used inside another constructor.

Example taken from this site .

  

If we create a method that receives an argument called   we want to assign to the class attribute, which is also called   connected, we must differentiate both showing who each one belongs to.   Since this refers to the context used, then we use it to   identify which bound will be the class attribute and bound without this   refers to the method parameter. What would result in this:

public class TV {
    //atributos
    int tamanho;
    int canal;
    boolean ligada;

    // método contrutor com parâmetro
    TV(boolean ligada) {
        this.ligada = ligada;
        /**
         * Onde this.ligada é o atributo
         * e ligada é o valor do parâmetro
         */
    }
}
    
21.09.2016 / 21:24
1

One easy way to understand it is:

When you have two variables in different scopes: one location (in one method) and one global (in the class). When you need to reference the global you use this, ex: this.var .

The staff set a good example with the methods. We use a lot of getters and setters.

    
21.09.2016 / 22:57