Re: java class heirarchy matching?
falcon wrote:
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).
Well, you already know the solution to your problem. Java method
selection is designed for OO progamming, and will tend to naturally do
what you need if you write your program that way.
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 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;}
}
The problem is that the run time use of object class to pick a method
only applies to the object containing the method, not to its parameters.
The compiler, when processing e.g. the value calls inside the LeafMult
value method, sees that it needs a value() method that can deal with
Root parameter, and selects the last one in Calculate.
Why not add an abstract "getValue" method to Root and put an
implementation in each subclass?
Patricia