Return to Snippet

Revision: 477
at July 15, 2006 08:30 by cetnar


Initial Code
// These are the the opcodes that our stack machine can execute.

   abstract static enum Opcode {

     PUSH(1),

     ADD(0),

     BEZ(1); // Remember the required semicolon after last enum value



     int numOperands;



     Opcode(int numOperands) { this.numOperands = numOperands; }



     public void perform(StackMachine machine, int[] operands) {

       switch(this) {

         case PUSH: machine.push(operands[0]); break;

         case ADD: machine.push(machine.pop( ) + machine.pop( )); break;

         case BEZ: if (machine.pop( ) == 0) machine.setPC(operands[0]); break;

         default: throw new AssertionError( );

       }

     }

   }

Initial URL

                                

Initial Description
In covering the more advanced features of enums, I can't leave out the ability to define value-specific class bodies. That sounds sort of fancy, but all it means is that each enumerated value within a type can define value-specific methods.

Initial Title
Value-specific class bodies in an enum

Initial Tags

                                

Initial Language
Java