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

Asked

Viewed 3,084 times

6

Example 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();          
    }
}

Only it doesn’t work. I just wanted to take the return of the other method and have it displayed with the method show().

How can I do this?

1 answer

8


Must use a design pattern called Fluent Interface, that links the methods so facilitate in the development, has a nice explanatory text about Interface Fluent and Builder Patterns in the Sopt that defines each one at a time of development, but let’s focus on their code.

Changes in the 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);
    }
}

and the method must be of the same class type and in its return refers to itself (this). Summary of the code that should be in the method:

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

Then it’ll work out like waiting:

package testarMetodo;

public class Teste 
{

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

Online Example

References:

  • 1

    Wow worked!...

  • 1

    @gonz, cool, take a read on the link has a slight differences mainly to Java, but I’m glad I could help.

  • 1

    Definitely friend. I will read yes. = ) When I get home...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.