001package edu.pdx.cs410J.j2se15;
002
003/**
004 * Demonstrates adding behavior to enumerated types.
005 *
006 * @author David Whitlock
007 * @version $Revision: 1.2 $
008 * @since Summer 2004
009 */
010public class NumericOperators {
011
012  private enum Operation {
013    PLUS {
014      double eval(double x, double y) {
015        return x + y;
016      }
017
018      char getSymbol() {
019        return '+';
020      }
021    },
022
023    MINUS {
024      double eval(double x, double y) {
025        return x - y;
026      }
027
028      char getSymbol() {
029        return '-';
030      }
031    },
032
033    TIMES {
034      double eval(double x, double y) {
035        return x * y;
036      }
037
038      char getSymbol() {
039        return '*';
040      }
041    },
042
043    DIVIDE {
044      double eval(double x, double y) {
045        return x / y;
046      }
047
048      char getSymbol() {
049        return '/';
050      }
051    };
052
053    /** Evaluates this operation for the given operands */
054    abstract double eval(double x, double y);
055
056    /** Returns the symbol that represent this operation */
057    abstract char getSymbol();
058  }
059
060  /**
061   * Evaluates several expressions using the {@link Operation}
062   * enumerated type.
063   */
064  public static void main(String[] args) {
065    Operation[] ops = { Operation.PLUS, Operation.MINUS,
066                        Operation.TIMES, Operation.DIVIDE };
067    for (Operation op : ops) {
068      System.out.println("5 " + op.getSymbol() + " 2 = " +
069                         op.eval(5, 2));
070    }
071  }
072
073}