What does this () alone do in the constructor?

12

In the code:

public Livro(Autor autor) { 
        this();
        this.autor = autor;
    }
    public Livro() { 
        this.isbn = "000-00-00000-00-0";
    }
    
asked by anonymous 23.01.2016 / 17:07

2 answers

9

It invokes the constructor that does not receive parameters, for example in the expression Livro l = new Livro(autor); what will occur is as follows:

  • new Livro(autor) will invoke the book constructor that receives an "author" as parameter, in the case public Livro(Autor autor) {
  • Internally the public Livro(Autor autor) { constructor will call this () that will invoke the constructor Book that does not receive any parameters, in the case public Livro() {
  • You could rewrite the code as equivalent:

    public Livro(Autor autor) { 
        this.isbn = "000-00-00000-00-0"; // ao invés de invocar o construtor Livro() estamos ralizando o que o tal construtor faz.
        this.autor = autor;
    }
    public Livro() { 
        this.isbn = "000-00-00000-00-0";
    }
    
        
    23.01.2016 / 17:12
    12

    this is a reference to the current object - the object whose method or constructor is being called to.

    When used inside one constructor it is used to call another constructor in the same class.

    Your Book class declares two constructors:

    public Livro(Autor autor)
    

    and

    public Livro()
    

    In the public Livro() constructor the isbn attribute is initialized, which must (I assume) be initialized regardless of the constructor used, hence the need to be called by the public Livro(Autor autor) constructor.

    Another common reason to use this is when a parameter of a method or constructor has a "name" equal to an attribute of the class. Notice the public Livro(Autor autor) constructor, whose parameter is autor , it was necessary to use this.autor = autor; to differentiate the attribute parameter.

    I think the code you posted is just an example, but here is a "more correct" way to declare constructors:

    public class Livro{
    
        private String isbn;
        private Autor autor; 
    
        public Livro(Autor autor, String isbn) { 
            this.autor = autor;
            this.isbn = isbn;
        }
    
        //Talvez passar ""(empty) na vez de "000-00-00000-00-0"
        public Livro(Autor autor) { 
            this(autor, "000-00-00000-00-0");
        }
    
        //Talvez não se devesse criar um livro sem autor.
        //Ou talvez sim, se o autor for desconhecido.
        public Livro() { 
            //Em vez de null talvez fosse preferível criar um Autor "default"(desconhecido)
            this(null);
        }
    }
    
        
    23.01.2016 / 17:23