java class heirarchy matching?
I have a heirrarchy of classes that is basically used to create a tree
of objects. I then want to 'evaluate' that tree of objects using
functions that are outside those classes (typically OO programmers
would probably make those functions methods of objects in the tree).
It seems to me that the function which matches the object tree is not
matching correctly. Following is a simplified version of my test code:
abstract class Root{
public abstract Root[] getRoots();
public String toString(){
StringBuffer str = new StringBuffer();
for(int i=0;i<getRoots().length;i++)
str.append(getRoots()[i].toString());
return " ("+this.getClass().getSimpleName()+ str+ " )";
}
}
class Leaf1 extends Root{
public Root[] getRoots(){ return new Root[]{}; }
}
class Leaf2 extends Root{
public Root[] getRoots(){ return new Root[]{}; }
}
class LeafPlus extends Root{
private Root a,b;
public LeafPlus(Root ra, Root rb){ a=ra; b = rb; }
public Root[] getRoots(){ return new Root[]{a,b}; }
}
class LeafMult extends Root{
private Root a, b;
public LeafMult(Root ra, Root rb){ a=ra; b = rb; }
public Root[] getRoots(){ return new Root[]{a,b}; }
}
class Calculate{
public static int value(Leaf1 l){return 1;}
public static int value(Leaf2 l){return 2;}
public static int value(LeafPlus l){return
Calculate.value(l.getRoots()[0])+Calculate.value(l.getRoots()[1]);}
public static int value(LeafMult l){return
Calculate.value(l.getRoots()[0])*Calculate.value(l.getRoots()[1]);}
//As I see it, this method should not have to exist, and even if it
does, it should never be called
public static int value(Root l){return 100;}
}
public class TestCases {
public static void main(String argv[]){
//Print out the tree, see the result below
System.out.println(new Leaf1());
System.out.println(new Leaf2());
System.out.println(new LeafPlus(new Leaf1(),new Leaf2()));
System.out.println(new LeafMult(new Leaf1(), new Leaf2()));
//Print out the result of the evaluation, see the result below
System.out.println(Calculate.value(new Leaf1()));
System.out.println(Calculate.value(new Leaf2()));
System.out.println(Calculate.value(new LeafPlus(new Leaf1(),new
Leaf2())));
System.out.println(Calculate.value(new LeafMult(new Leaf1(), new
Leaf2())));
}
}
//Result
(Leaf1 )
(Leaf2 )
(LeafPlus (Leaf1 ) (Leaf2 ) )
(LeafMult (Leaf1 ) (Leaf2 ) )
1
2
200 <= I want the result to be '3' (1+2==3)
10000 <= I want the result to be '2' (1 * 2 == 2)
I have tried some variations such as making the Calculate class
non-static, which still doesn't give the answer I expect. The
"value(Root l)" methods is called from LeafMult and LeafPlus, even
though within those methods the Root objects are correctly recognized
as either Leaf1 or Leaf2 (according to some print statements which I
took out). Any ideas?