java – Use of auto reference

Question:

About the use of self-reference this , I wanted to know what the difference is:

public static class Aluno{
    private String nome;

    public String getNome(){
        return nome;
    }
    public Aluno(){
        this.nome="abc";
    }
}  

and to do:

public static class Aluno{
    private String nome;

    public String getNome(){
        return nome;
    }
    public Aluno(){
        nome="abc";
    }
}

what is the difference between this.nome and nome .

Answer:

In the example shown there is none, both refer to the nome field.

However, there are situations where this does not happen.
See the case of this example:

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

Here it is necessary to distinguish between the field and the method parameter.

Scroll to Top