我在驱动程序类的内部方法中有此代码(相关代码段):
switch (op) {
case "+":
arithStack.push(new AddExpression(leftExpression, rightExpression));
// System.out.println(arithStack.peek() + " :top of Stack");
break;
case "-":
arithStack.push(new SubExpression(leftExpression, rightExpression));
break;
case "*":
arithStack.push(new MultExpression(leftExpression, rightExpression));
break;
case "/":
arithStack.push(new DivExpression(leftExpression, rightExpression));
break;
case "^":
arithStack.push(new PowExpression(leftExpression, rightExpression));
break;
}
子类(AddExpression,SubExpressino等)是称为ArithBinaryExpression的抽象基类的子类。 子类之一的实现如下所示(除算术运算外,与其他子类相同):
public static class AddExpression extends ArithBinaryExpression {
public AddExpression(ArithExpression leftExp, ArithExpression rightExp) {
super(leftExp, rightExp);
}
public double result() {
ArithExpression rightExp = getRightExpression();
ArithExpression leftExp = getLeftExpression();
return rightExp.result() + leftExp.result();
}
public String toString() {
return "Expression: " + "(" + leftExpression.toString() + " + " + rightExpression.toString() + ")";
}
}
在这些子类构造函数的主要调用中,编译器给我一个错误:
arithStack.push(new AddExpression(leftExpression, rightExpression));
在这里编译器状态:
AddExpression无法解析为类型。我该如何解决?
更新:
(HERE是ArithBinaryExpression类)
public abstract class ArithBinaryExpression implements ArithExpression {
protected static ArithExpression leftExpression;
protected static ArithExpression rightExpression;
public boolean isSimple() {
boolean isSimple = false;
if (leftExpression instanceof ArithValue && rightExpression instanceof ArithValue) {
isSimple = true;
}
return isSimple;
}
// constructor
public ArithBinaryExpression(ArithExpression left, ArithExpression right) {
if (left == null) {
leftExpression = new ArithValue(0);
}
else
leftExpression = left;
if (right == null) {
rightExpression = new ArithValue(0);
}
else
rightExpression = right;
}
// end constructor
// accessors
public ArithExpression getLeftExpression() {
return leftExpression;
}
public ArithExpression getRightExpression() {
return rightExpression;
}
答案 0 :(得分:1)
从类定义中删除static
:
public class AddExpression extends ArithBinaryExpression {
public AddExpression(ArithExpression leftExp, ArithExpression rightExp) {
super(leftExp, rightExp);
}
public double result() {
ArithExpression rightExp = getRightExpression();
ArithExpression leftExp = getLeftExpression();
return rightExp.result() + leftExp.result();
}
public String toString() {
return "Expression: " + "(" + leftExpression.toString() + " + " +
rightExpression.toString() + ")";
}
public static void main(String args[]) {
// create it here using new AddExpression ...
}
}
Java不允许您创建顶级静态类。在Java中,如果new
是static
,则不能使用public class AddExpression
创建新对象。
public static void main(String args[]) {
// create it here using new AddExpression ...
}
必须是文件 addexpression.java 中唯一的公共类,并且必须正确导入或定义所有其他类。
要查看它是否正确创建,请使用您的
None