UP | HOME

Operation Enum

1. Example

public enum Operation {
│   PLUS {
│   │   double eval(double x, double y) { return x + y; }
│   },
│   MINUS {
│   │   double eval(double x, double y) { return x - y; }
│   },
│   TIMES {
│   │   double eval(double x, double y) { return x \* y; }
│   },
│   DIVIDED_BY {
│   │   double eval(double x, double y) { return x / y; }
│   };
│
│   // Perform the arithmetic operation represented by this constantabstract double eval(double x, double y);
│   public static void main(String args[]) {
│   │  double x = 2.0;
│   │  double y = 4.0;
│   │  for (Operation op : Operation.values())
│   │      System.out.println(x + " " + op + " " + y + " = " + op.eval(x, y));
│   │ }
}

The document says it is anticipated that the need for this will be rare and it is a bit tricky. Why would people think it is tricky?

2. Reference