Doubts paramparing in Java

2

Personal speech,

I am in doubt about 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.Envia method receives only one object of type Job as argument, what behavior of the application in this case - when I open a "{}" and call other methods?

Could you help me with pfv examples.

Thank you in advance.

    
asked by anonymous 28.10.2015 / 23:39

1 answer

6

Your OpUtil.Envia method is receiving an object of type Job with two methods overrides (% with% and% with%).

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

A simple example, which illustrates the same situation well:

    public class Mensagem {
        public Mensagem() {}

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

Main test class:

   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 overwritten method!

    
29.10.2015 / 03:08