We Recommend

Java How to Program Java How to Program
Takes a new tools-based approach to Web application development that uses Netbeans 5.5 and Java Studio Creator 2 to create and consume Web Services. Features new AJAX-enabled, Web applications built with JavaServer Faces (JSF), Java Studio Creator 2 and the Java Blueprints AJAX Components. Includes new topics throughout, such as JDBC 4, SwingWorker for multithreaded GUIs, GroupLayout, Java Desktop Integration Components (JDIC), and much more.


Posted By

cetnar on 07/15/06


Tagged

tiger enum methods


Versions (?)


Who likes this?

1 person has marked this snippet as a favorite

xaviaracil


Value-specific class bodies in an enum


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.


  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 

You need to login to post a comment.