## Polymorphism

So far our methods just do arithmetic on two complex numbers. It’s not uncommon to want to multiply a complex number by a real number. To add this capability to our class we’ll add the following method:

public Complex Times (double x) {

return new Complex(u*x, v*x);

}

Here’s a simple test program for your new method:

class RealComplex {

public static void main (String args[]) {

Complex v, z;

double x = 5.1;

v = new Complex(3,-4.5);

System.out.println(”v: ” + v);

System.out.println(”x: ” + x);

z=v.Times(x);

System.out.println(”v * x: ” + z);

}

}

The astute among you may be saying to hold on here, we’ve redefined the Times method. Now how can we multiply two complex numbers? However there’s really no problem. The compiler notices that the arguments of the two methods named Times (not the same as the arguments of the two complex numbers but unfortunately the terminology fails us here) are different. One multiplies two complex numbers, the other multiplies a real number and a complex number. The compiler is smart enough to figure out which version of Times to use when. This is called method overloading or polymorphism.

In some object-oriented languages like C++ you can not only overload methods but even operators like + and =. However while this makes numeric classes like complex numbers easier to work with, it tends to lead to unreadable and unmaintainable code for non-numeric classes. Therefore Java’s designers elected not to add this feature to the language. As you can see from our example, with a little forethought you really don’t lose very much without operator overloading.

Exercises

1. Add a method to the Complex class that adds a real number to a complex number and returns a complex number.

2. Add methods for subtracting a real number from a complex number and for subtracting a complex number from a real. Be careful since subtraction, unlike addition, is not commutative.

3. Add methods for dividing a real by a complex number and for dividing a complex number by a real. Be careful since division, unlike multiplication, is not commutative.