How to call from a constructor to another Java Constructor

1

I have these 3 constructors in a java class, as it would be the correct way to make one call the other, that is, call the default, that it calls the next one with fewer parameters and the latter to which it has all the parameters example:

    public Correo(String from, String to, String asunto, String texto) {
        this.from = from;
        this.to = to;
        this.asunto = asunto;
        this.texto = texto;
        this.leido = false;
        this.fecha.getDate();
    }


  public Correo() {  }

  public Correo(String from) {
        this.from = from;
}
    
asked by Maxi Hernandez 24.11.2017 в 02:26
source

1 answer

3

You can call a constructor from another constructor using the keyword this . The only restriction in its use is that it must be the first statement in the constructor.

Example:

public Correo(String from, String to, String asunto, String texto) {
    this.from = from;
    this.to = to;
    this.asunto = asunto;
    this.texto = texto;
    this.leido = false;
}

public Correo() {
    this("from"); // asignas los valores por defecto deseado
}

public Correo(String from) {
    this(from, "tu", "asunto", "texto"); // asignas los valores por defecto deseado
}
    
answered by 24.11.2017 в 02:46