The Java Course provides a general introduction to programming in Java. It is based on A.B. Downey's book, How to Think Like a Computer Scientist. Click here for details.


Another Function on Complex Numbers

Another operation we might want to perform on complex numbers is addition. You can add complex numbers by adding the real parts and adding the imaginary parts. Written as a class method, that looks like:

  public static Complex add (Complex a, Complex b) {
    return new Complex (a.real + b.real, a.imag + b.imag);
  }

To invoke this method, we would pass both operands as arguments:

    Complex sum = add (x, y);

Written as an object method, it would take only one argument, which it would add to the current object:

  public Complex add (Complex b) {
    return new Complex (real + b.real, imag + b.imag);
  }

Again, we can refer to the instance variables of the current object implicitly, but to refer to the instance variables of b we have to name b explicitly using dot notation. To invoke this method, you invoke it on one of the operands and pass the other as an argument.

    Complex sum = x.add (y);

From these examples you can see that the current object (this) can take the place of one of the parameters. For this reason, the current object is sometimes called an implicit parameter.



Last Update: 2011-01-24