Doubt parameter passage in Java

Asked

Viewed 50 times

2

Personal talk,

I am doubtful in the following method:

 /**
     * Metodo x
     */
public Exit Method(String n) {
    final Ent y = new Ent();
    y.setn(n);
    Exit res = OpUtil.Envia(new Job() {
        @Override
        public Exit run(OpInt oi) throws RemoteException {
            Exit res = oi.execute(y);
            if (OpUtil.Ok(res)) {
                //...
            }
            return res;
        }

        @Override
        public ExitList runAsList(OpInt oi)
                throws RemoteException {
            // TODO Auto-generated method stub
            return null;
        }
    });
    return res;
}

The Oputil.Send method receives only one Job type object as argument, what is the behavior of the application in this case - when I open a "{}" and call other methods?

Could you help me with examples pfv.

Thanks in advance.

1 answer

6


Your method OpUtil.Envia is receiving an object of the type Job with two methods superscripts (run and runAsList).

This means that if these two Job methods are invoked at some point by the Send method, they will react the way they were implemented when passed as argument, rather than reacting the way they were implemented in the original class.

A simple example, which illustrates the same situation:

    public class Mensagem {
        public Mensagem() {}

        public void enviarMsg() {
            System.out.println("Mensagem enviada pelo método original");
        }
    }

Main class for testing:

   public class Principal {

        import Mensagem;

        public static void main(String[] args) {

              //Criando uma instância de Mensagem normalmente
              Mensagem objeto = new Mensagem();

              //Criando uma instância de Mensagem com o método
              //enviarMsg() sobrescrito
              Mensagem objetoSobrescrito = new Mensagem() {
                    @Override
                    public void enviarMsg() {
                        System.out.println("Agora a mensagem é enviada pelo método sobrescrito!");
                    }
              };

              //Testando os resultados
              objeto.enviarMsg();
              objetoSobrescrito.enviarMsg();
        }
   }

Data output:

Message sent by original method
Now the message is sent by the superscript method!

Browser other questions tagged

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