-1

我有一个类表达式:

public class Expression < E extends Number, V extends Number >
{
   public Expression(E lV, OPERATION operation, V rV) {
   }

   public Expression(Expression< E, V > lE, OPERATION operation, Expression< E, V > rE) {
   }
}

Expression.java 编译没有错误。

这是我的主要课程代码。

public static void main(String[] args)
{
        // Line 1. 
    refactored.Expression< ?, ? > ex1 = new refactored.Expression< Double, Float >(10d, OPERATION.PLUS, 10f);

        // Line 2.
    refactored.Expression< ?, ? > ex2 = new refactored.Expression< Double, Float >(-3d, OPERATION.MUL, 1f);

        // Line 3.
    refactored.Expression< ?, ? > ex3 = new refactored.Expression< refactored.Expression< Double, Float >, refactored.Expression< Double, Float > >(ex1, OPERATION.MINUS, ex2);
}

第 3 行没有编译,它说:

Exception in thread "main" java.lang.Error: Unresolved compilation problems: 
The constructor Expression<Expression<Double,Float>,Expression<Double,Float>>(Expression<capture#1-of ?,capture#2-of ?>, OPERATION, Expression<capture#3-of ?,capture#4-of ?>) is undefined
Bound mismatch: The type Expression<Double,Float> is not a valid substitute for the bounded parameter <E extends Number> of the type Expression<E,V>
Bound mismatch: The type Expression<Double,Float> is not a valid substitute for the bounded parameter <V extends Number> of the type Expression<E,V>

它出什么问题了?

4

3 回答 3

3

表达式不扩展数字,因此它不是合法的类型参数。

编辑 - 解决评论
我不确定你为什么需要通用解决方案......
你可以有类似的东西

interface Expression {
  Number compute();
}

class AtomicExpression implements Expression {
  private final Number number;
  AtomicExpression(Number number) {
    this.number = number;
  }
  public Number compute() {
    return number;
  }
}

class BinaryExpression implements Expression {
  private final Expression expr1;
  private final Expression expr2;
  private final Operator op;
  AtomicExpression(Expression expr1, Expression expr1. Operator op) {
    this.expr1 = expr1;
    this.expr2 = expr2;
    this.op = op;
  }
  public Number compute() {
    return op(expr1.compute(), expr2.compute());
  }
}
于 2013-09-16T13:35:25.500 回答
0

重构。表达式< ?, ? > ex3 = new refactored.Expression < Double, Float>(ex1, OPERATION.MINUS, ex2);

这应该有效。

于 2013-09-16T13:41:14.633 回答
0

从你得到的错误中可以明显看出这Expression<?, ?>不是 Number 的子类。如果你真的想在你的构造函数中接受表达式,那么你需要从泛型中删除上绑定参数(数字)。

像这样的东西应该适合你:

public class Expression <E, V> {
    public Expression(E lV, OPERATION operation, V rV) {}
    public Expression(Expression< E, V > lE, OPERATION operation, Expression< E, V > rE) {}
}

更新:这应该可以工作:

Expression< Double, Float > ex1 = new Expression< Double, Float >(10d, OPERATION.PLUS, 10f);

Expression< Double, Float > ex2 = new Expression< Double, Float >(-3d, OPERATION.MUL, 1f);

Expression< ?, ? > ex3 = new Expression
 < Expression< Double, Float >, Expression< Double, Float > >(ex1, OPERATION.MINUS, ex2);
于 2013-09-16T13:42:34.827 回答