i have a math class that stores representation of expressions in n-array lists
i currently have three classes AdditionArray MultipleArray and Variable they all implement my Number interface.
public interface Number {
public Number Multiply(Number number);
in the classes that implement Number i have overloaded opertions like Multiply for example
public class MultipleArray extends ArrayList<Number> implements Number{
public Number Multiply(AdditionArray number);
public Number Multiply(Number number){throw new Exception("woops");}
the thing is java is not automatically calling the correct overloaded function at runtime. it seams to be figuring it out at compile time
for example
Number someNumber = new MultipleArray();
Number someOtherNumber = new AdditonArray();
MultipleArray result2 = someNumber.Multiply(someOtherNumber); //calls the correct function
Number result2 = someNumber.Multiply(someOtherNumber); // throws the woops exception
why is java doing this. and is there another way i can implement this. some sort of factory for example?
Cheers,
Mark
As Bill K said, Java determines this at compile time, and this is by design.
The really standard way to implement this is to have code in the overloaded method with the supertype that checks the type of the subclass and delegates with a cast or throws an exception as appropriate.
Using Generics is another option, which will improve your type safety, but I don’t know enough about your code to say if it would work all around. A generic number interface might look like this:
Generics can get weird around the edges, so it might be worth it to just give up on the type safety and go with checking the type of the parameter.