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.

Complex Numbers

As a running example for the rest of this chapter we will consider a class definition for complex numbers. Complex numbers are useful for many branches of mathematics and engineering, and many computations are performed using complex arithmetic. A complex number is the sum of a real part and an imaginary part, and is usually written in the form x + yi, where x is the real part, y is the imaginary part, and i represents the square root of -1. Thus, i · i = -1.

The following is a class definition for a new object type called Complex:

class Complex
  // instance variables
  double real, imag;

  // constructor
  public Complex () {
    this.real = 0.0;  this.imag = 0.0;

  // constructor
  public Complex (double real, double imag) {
    this.real = real;  this.imag = imag;

There should be nothing surprising here. The instance variables are two doubles that contain the real and imaginary parts. The two constructors are the usual kind: one takes no parameters and assigns default values to the instance variables, the other takes parameters that are identical to the instance variables. As we have seen before, the keyword this is used to refer to the object being initialized.

In main, or anywhere else we want to create Complex objects, we have the option of creating the object and then setting the instance variables, or doing both at the same time:

    Complex x = new Complex ();
    x.real = 1.0;
    x.imag = 2.0;
    Complex y = new Complex (3.0, 4.0);

Last Update: 2011-01-24