Value-specific class bodies in an enum


/ Published in: Java
Save to your folder(s)

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.


Copy this code and paste it in your HTML
  1. // These are the the opcodes that our stack machine can execute.
  2.  
  3. abstract static enum Opcode {
  4.  
  5. PUSH(1),
  6.  
  7. ADD(0),
  8.  
  9. BEZ(1); // Remember the required semicolon after last enum value
  10.  
  11.  
  12.  
  13. int numOperands;
  14.  
  15.  
  16.  
  17. Opcode(int numOperands) { this.numOperands = numOperands; }
  18.  
  19.  
  20.  
  21. public void perform(StackMachine machine, int[] operands) {
  22.  
  23. switch(this) {
  24.  
  25. case PUSH: machine.push(operands[0]); break;
  26.  
  27. case ADD: machine.push(machine.pop( ) + machine.pop( )); break;
  28.  
  29. case BEZ: if (machine.pop( ) == 0) machine.setPC(operands[0]); break;
  30.  
  31. default: throw new AssertionError( );
  32.  
  33. }
  34.  
  35. }
  36.  
  37. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.