/ Published in: Java
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.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
// 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( ); } } }