Ok, I have 3 classes, An abstract one (called 'NumberType'), and two standard ones (called 'Real' & 'Complex'). The two standard classes are child classes of the abstract class.
As you may have guessed, these things do basic arithmetic on real & complex numbers. Inside each, are overloaded methods handling all combinations of the basic operations - such as a 'real added to a real', a 'real added to a complex', a 'complex added to a real', a 'complex added to a complex' and so on..
And then, inside the NumberType class, I have abstract methods such as:-
abstract NumberType add(Real number);
abstract NumberType add(Complex number);
The reason that the return type here is 'NumberType', (and also the entire point of this class's existence anyway), is that upfront, there would be no way of knowing what type of number would be returned by this method. For instance, two complex numbers added, may in some instances, return a real number. And similar for other combinations.
Now, I also have included a non-abstract method in the NumberType class, that handles
a NumberType added to a NumberType. It goes like this:-
Now, finally, the point of my entire question. Is there anyway of doing this without having to resort to using the rather frowned-upon 'instanceOf' statement? I have tried a few things, without success, such as generics. But cannot get anything to work, without using instanceOf.public NumberType add(NumberType number) { if (number instanceof Real == true) { return(this.add((Real)number)); } else { if (number instanceof Complex == true) { return(this.add((Complex)number)); } } }
Thanks