Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

340
Visualizações
What is the difference between this.setMethod(parameter) and setMethod(parameter) in a constructor? [Java]

I have been trying to learn about classes and objects for the last few days and I realized that using "this.set" and "set" inside a constructor made no apparent difference. To clarify

public Movie(String title,String director, String rating) {
        setTitle(title); 
        setDirector(director);
        setRating(rating);

and

public Movie(String title,String director, String rating) {
        this.setTitle(title); 
        this.setDirector(director);
        this.setRating(rating);

made no difference while running.

What is the difference, if there is any and which one is better practice?

I was expecting there to be some kind of error, but it worked completely the same. In addition, my instructor does not use "this." while putting a setter inside a constructor in his examples.

Thanks.

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

There is no need to use this when calling the setter methods in your example (and it's not standard practice to do so). However, it is necessary to use this if you want to set a field with the same name as a variable in the constructor. For example:

public class Movie {
    private final String title;

    public Movie(String title) {
        this.title = title;
    }
}

If you don't specify this.title, it will think you are trying to assign the title variable to itself.

The keyword this is also needed to distinguish different implementations of methods when your class has extended another class (e.g. you can call this.method() or super.method().)

over 4 years ago · Santiago Trujillo Relatório

0

With this.* you are calling the method located at "this" instance. When inheriting from a class having implemented the same method(s), you also have the opportunity to call super.setTitle().

Or with an example:

class Foo
{
    public int baz()
    {
        return -1;
    }
}

class Bar extends Foo
{
    private Bar()
    {
        super.baz(); // returns -1
        this.baz(); // returns 1
    }

    public int baz()
    {
        return 1;
    }
}
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda