I need help with a problem that I am facing generics in Java. I write this computer algebra system, where the user enters a mathematical expression, and the system works with it in different ways (expand it, simplify it, etc.). It worked great for expressions containing natural numbers, and I wanted to expand it to work with mathematical sets. Instead of + you will have an intersection operator, etc.
At first I started recording everything for kits, but then I realized that this was probably not very good, and started using generics.
Instead of having one parsing tree, for example MathExpr, one, like SetExpr, I thought I could just create a common one Expression<T>and build a base class Numberand a base class Set.
To try to clarify, I want a mathematical expression like (2 * a) + (3 + 2) to be an instance of the class Expression<Number>, and an expression like (A ∪ B) ∩ C to be an instance Expression<Set>. Then I can perform various operations, for example, calculate the depth, etc.
Operation + is implemented as one class, * as one class, etc. Both of these classes are subclasses of the abstract class with a name TwoExpr, which, in turn, is a subclass of the abstract class Expr. This is how I did it now, and everything is working fine.
When I wanted to change my code, I made a general class Expr. This is Expr<T>. I also changed TwoExpr to TwoExpr<T>and created a base class Number.
The problem is that now I can not imagine type objects Sum<Number>.
"Type mismatch: cannot convert from Sum to Expr<Number>". Sum TwoExpr<Number>, , , Expr<Number>. , Sum generic Sum<Number>, .
,
Expr zero= new Leaf(0);
Variable a = new Variable("a");
Expr aPlusZero = new Sum(a, zero);
generics, :
Expr<Number> zero= new Leaf<Number>(new Number(0));
Variable<Number> a = new Variable<Number>("a");
Expr<Number> APlusZero=new Sum(a,zero);
, Sum(a,zero) Expr<Number>, Sum
public class Sum extends TwoExpr<Number> {
public Sum(Expr<Number> a, Expr<Number> b) {
super(a, b);
}
...
}
TwoExpr
public abstract class TwoExpr<T> extends Expr<T> {
protected Expr<T> a;
protected Expr<T> b;
public TwoExpr(Expr<T> a, Expr<T> b) {
this.a=a;
this.b=b;
}
...
}
, Lizkows . Number ( Object) .
, , , , . - , ? , , - .
.