Call a method that calls another method of the same class?

6

Example I have the class Metodo :

public class Metodo {

    private String string;

    public String mostrar(String nome, String sobrenome){
        this.string = "Nome: " + nome + "Sobrenome: " + sobrenome;

        return string;
    }

    public void show(){
        System.out.println(this.string);
    }
}

And the class that tests this method:

package testarMetodo;

    public class Teste {

    public static void main(String[] args) {            
        Metodo metodo = new Metodo();
        metodo.mostrar("Aline", "Gonzaga").show();          
    }
}

It just does not work. I just wanted to get the return of the other method and have display with the method show() .

How can I do this?

    
asked by anonymous 13.11.2016 / 14:21

1 answer

8

You should use a project pattern Influence Interface , which chains methods in a way that facilitates development , has a nice explanatory text about Interface Fluent and Builder Patterns on SOPt in> that defines each one at a time of development, but let's focus on your code.

Changes in class Metodo :

public class Metodo
{

    private String string;
    public Metodo mostrar(String nome, String sobrenome)
    {
         this.string = "Nome: " + nome + " Sobrenome: " + sobrenome;
         return this;
    }
    public void show()
    {
        System.out.println(this.string);
    }
}

The method must be of the same class type and on its return it references itself ( this ). Summary of the code that should be in the method:

public Metodo mostrar(String nome, String sobrenome)
{
    //code ...
    return this;
}

It will work as expected:

package testarMetodo;

public class Teste 
{

    public static void main(String[] args) 
    {
        Metodo metodo = new Metodo();
        metodo
            .mostrar("Aline", "Gonzaga")
            .show(); 
    }
}

Example Online

References:

13.11.2016 / 14:25