SE450: Enumerations: Enumeration with polymorphic methods [24/32] Previous pageContentsNext page

Recall the code we had for expression trees: file:ExprFactory.java [source] [doc-public] [doc-private]

file:Op.java [source] [doc-public] [doc-private]
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
package enumeration2;

public enum Op {
  ADD("+") { public int eval(int x, int y) { return x + y; } },
  SUB("-") { public int eval(int x, int y) { return x - y; } },
  MUL("*") { public int eval(int x, int y) { return x * y; } },
  DIV("/") { public int eval(int x, int y) { return x / y; } };

  private final String name;
  private Op(String name) { this.name = name; }

  public String toString() { return name; }
  public abstract int eval(int x, int y);
}

file:ExprFactory.java [source] [doc-public] [doc-private]
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
package enumeration2;

public class ExprFactory {
  private ExprFactory() {}
  static public Expr newConst(int v) {
    return new Const(v);
  }
  static public Expr newPlus(Expr l, Expr r) {
    return new BinOp(l, Op.ADD, r);
  }
  static public Expr newMinus(Expr l, Expr r) {
    return new BinOp(l, Op.SUB, r);
  }
  static public Expr newMult(Expr l, Expr r) {
    return new BinOp(l, Op.MUL, r);
  }
  static public Expr newQuot(Expr l, Expr r) {
    return new BinOp(l, Op.DIV, r);
  }
}

Here is the Java 1.4 version:

file:Op.java [source] [doc-public] [doc-private]
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package enumeration;

public abstract class Op {
  private final String name;
  Op(String name) { this.name = name; }
  public String toString() { return name; }

  public abstract int eval(int x, int y);

  public static final Op ADD = new OpAdd();
  public static final Op SUB = new OpSub();
  public static final Op MUL = new OpMul();
  public static final Op DIV = new OpDiv();
}

final class OpAdd extends Op {
  OpAdd() {  super("+"); }
  public int eval(int x, int y) { return x+y; }
}
final class OpSub extends Op {
  OpSub() {  super("-"); }
  public int eval(int x, int y) { return x-y; }
}
final class OpMul extends Op {
  OpMul() {  super("*"); }
  public int eval(int x, int y) { return x*y; }
}
final class OpDiv extends Op {
  OpDiv() {  super("/"); }
  public int eval(int x, int y) { return x/y; }
}

Previous pageContentsNext page