这是我的大学课程。
我有这个顶级抽象类Expression.java(由教授提供):
public abstract class Expression {
public abstract int eval();
public abstract String toString();
}
BinaryExpression.java(也由教授提供),它扩展了Expression.java:
public abstract class BinaryExpression extends Expression {
protected Expression left;
protected Expression right;
public BinaryExpression (Expression l, Expression r) {
left = l;
right = r;
}
public abstract int eval();
public abstract String toString();
}
最后Add.java(我写了这篇文章)扩展了BinaryExpression.java:
public class Add extends BinaryExpression {
//Fields
protected Expression left;
protected Expression right;
//Constructor
public Add(Expression l, Expression r) {
left = l;
right = r;
}
//Methods
public int eval() {
return left.eval()+right.eval();
}
public String toString() {
return left + "+" + right;
}
}
还提供了测试人员Test.java。还有其他三个类扩展了BinaryExpression,Subtract,Multiply和Divide,但它们实际上与Add相同。 Plus和Minus只存储一个负值或正值。
public class Test {
public static void main (String [] args) {
Expression s1 = new SimpleExpression(10);
Expression s2 = new SimpleExpression(-3);
System.out.println("s1: " + s1 + " = " + s1.eval());
System.out.println("s2: " + s2 + " = " + s2.eval());
Expression u1 = new Plus(s2);
Expression u2 = new Minus(s1);
System.out.println("u1: " + u1 + " = " + u1.eval());
System.out.println("u2: " + u2 + " = " + u2.eval());
Expression b1 = new Add(u1, s2);
Expression b2= new Subtract(s1, u2);
Expression b3= new Multiply(u1, b1);
Expression b4= new Divide(u2, b3);
System.out.println("b1: " + b1 + " = " + b1.eval());
System.out.println("b2: " + b2 + " = " + b2.eval());
System.out.println("b3: " + b3 + " = " + b3.eval());
System.out.println("b4: " + b4 + " = " + b4.eval());
Expression e = new Minus( new Multiply(b3, b2));
System.out.println("e: " + e + " = " + e.eval());
// example given in the assignment
e = new Divide(new Add(new Minus(new SimpleExpression (10)),
new SimpleExpression (50)),
new Minus(new Multiply(new SimpleExpression(5),
new Minus (new SimpleExpression (3)))));
System.out.println("Another e: " + e + " = " + e.eval());
}
}
当我编译Test.java时,我得到了这个错误(和Subtract,Multiply和Divide类似的错误):
./Add.java:8: cannot find symbol
symbol : constructor BinaryExpression()
location: class BinaryExpression
public Add(Expression l, Expression r) {
发生了什么?
答案 0 :(得分:4)
根本原因在这里
public Add(Expression l, Expression r) {
left = l;
right = r;
}
您的子类正在尝试隐式调用无参数的超级构造函数。您的父类没有这样的无参数构造函数。因此,请调用其现有构造函数
public Add(Expression l, Expression r) {
super(l, r);
left = l;
right = r;
}
此外,您还要重新声明left
课程中的right
和Add
字段。这样做没有意义。您的子类已有权访问其父类left
的{{1}}和right
字段。