简体   繁体   中英

Why should I create a new object reference to do a function call opposed to using an existing one?

My variable program is a object with a list of ByteCode subclass objects which I want to execute using an abstract method named execute() . The getNextCode() gets the next ByteCode object in that list.
My question is, why would I want to create a new instance of ByteCode just to call the execute() method instead of just referencing the instance in the list and calling the execute method the way the second code box does? Is there a difference? Is it for some reason safer to create a new instance? Does it have something to do with the process of dynamic binding here?

highlighting the two statements

program.getNextCode(pc).execute(this);

 ByteCode code = program.getNextCode(pc); 
 code.execute(this);


  public void executeProgram() { 
          runStack = new RunTimeStack(); 
          returnAddrs = new Stack(); 
          isRunning = true;
          pc = 0;

           while (isRunning) {
            ByteCode code = program.getNextCode(pc); 
            code.execute(this);


   public void executeProgram(){

        runStack = new RunTimeStack();
        returnAddrs = new Stack();
        isRunning = true;
        pc = 0;

        while(isRunning){
        program.getNextCode(pc).execute(this);

In this piece of code:

 ByteCode code = program.getNextCode(pc); 

You are not creating a new ByteCode instance, you are just referencing the instance that program.getNextCode(pc ) returns.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM