Call method with parameter of another method in Java?

Asked

Viewed 815 times

-2

I would call a method with parameter being an object of another class, but this object is created in a previous method?

Example:

Classea:

Public void cadastrar (Cliente cliente){
      System.out.println (cliente.getNome());

}

Classeb:

Public void metodoDois (){

 Cliente cliente = new Cliente();

}

ClasseA chamada = new classeA();
    Chamada.cadastrar(cliente);
  • The method metodoDois the way it is written is largely useless, except for an eventual side effect not clear that may arise at the instantiation cliente. Local variables (and arguments as well) can only be used within the scope of the function. Your example is not clear what you want.

1 answer

0


The way it is is not possible

You can change the metodoDois() and pass it by parameter to the method cadastrar():

Classea:

Public void cadastrar (Cliente cliente){
    System.out.println (cliente.getNome());
}

Classeb:

Public Cliente metodoDois() {
    return new Cliente();
}

ClasseA chamada = new classeA();
Chamada.cadastrar(metodoDois());

Or create a variable outside the function metodoDois() which will be modified in the function call and then pass as parameter of the cadastrar():

Classea:

Public void cadastrar (Cliente cliente){
    System.out.println (cliente.getNome());
}

Classeb:

Cliente cliente;

Public void metodoDois() {
    this.cliente = new Cliente();
}

ClasseA chamada = new classeA();
metodoDois();
Chamada.cadastrar(cliente);

Browser other questions tagged

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