I have a set of derived classes (mathematical values, such as Length, Angle, Value) and I'm defining calculation functions for them. The overloaded functions aren't being called as I expected. Problem boiled down to simple form...
public abstract class Operand {
public abstract Operand multiply(Operand other);
public static void main(String[] args) {
try {
Operand x = new Value(5);
Value y = new Value(6);
Operand z = x.multiply(y);
System.out.println(z);
} catch (Throwable e) {
e.printStackTrace(System.out);
}
}
}
public class Value extends Operand {
final double value;
Value(double arg) { value = arg; }
@Override
public Operand multiply(Operand other) { // type of other not known
System.out.println("dispatch of " + getClass().getSimpleName() +
".multiply(" + other.getClass().getSimpleName()+")");
return other.multiply(this); // dispatch to handler through polymorphism.
}
public Operand multiply(Value other) { // this and other are specific type
System.out.println("calculation of " + getClass().getSimpleName() +
".multiply(" + other.getClass().getSimpleName()+")");
return new Value(value*other.value);
}
@Override
public String toString() {
return Double.toString(value);
}
}
Hopefully you can see that I basically want multiple type derived from "Operand" and I want to be able to do:
Operand a;
Operand b;
Operand a.function(b)
And have the right function eventually called for the underlying specific type.
However, Java is not picking of the type of this in the dispatch and applying it on the subcall. I thought java was supposed to pick the most specific method prototype when the class is know. Instead I'm getting infinite recursive calls to the dispatch function:
dispatch of Value.multiply(Value)
dispatch of Value.multiply(Value)
dispatch of Value.multiply(Value)
dispatch of Value.multiply(Value)
...
this
is certainly known in this case to be Class==Value
so why isn't other.multiply(this)
resulting in Value multiply(Value)
being the chosen prototype?
What understanding of Java am I missing here?