/*
 * Complex.java by Richard J. Davies
 * from `Introductory Java for Scientists and Engineers'
 * chapter: `Object Orientation'
 * section: `Example - Complex Numbers'
 *
 * This program implements a class `Complex' with non-static members and so
 * enables us to create objects of a new `Complex' data type. It is only an
 * example and does not implement all of the features that you would want from
 * a complex number. See `JNL, a Numerical Library for Java' from a fuller
 * class. This is intended as a first example of an object that we ourselves
 * have written.
 */
public class Complex
{
  // Declare the data variable for the type
  public double realpart;
  public double imagpart;

  // Default constructor sets value to 0 + 0i
  public Complex()
  {
    realpart = 0;
    imagpart = 0;
  }

  // Constructor with user specified value
  public Complex(double r, double i)
  {
    realpart = r;
    imagpart = i;
  }

  // Method to add `other' to this object
  public void add(Complex other)
  {
    realpart += other.realpart;
    imagpart += other.imagpart;
  }

  // Method to multiply `other' into this object
  public void multiply(Complex other)
  {
    // Declare temporary storage for calculation
    Complex ans = new Complex();

    // Calculate
    ans.realpart = realpart * other.realpart
                   - imagpart * other.imagpart;  
    ans.imagpart = realpart * other.imagpart
                   + imagpart * other.realpart;

    // Copy value into this object.
    realpart = ans.realpart;
    imagpart = ans.imagpart;
  }

  // Main method. Static and so independent
  // of the definition of the object type.
  public static void main(String[] argv)
  {
    // Declare and create some objects
    Complex a = new Complex();
    Complex b = new Complex(4.7, 3.2);
    Complex c = new Complex(3.1, 2.4);

    // Perform some arithmetic
    a.add(b);
    c.multiply(a);

    // Extract the answer
    System.out.print(c.realpart + " + ");
    System.out.println(c.imagpart + "i"); 
  }
}

