/** * Purpose: A class from which objects might be created, which behave like * complex numbers. Private variables are used to demonstrate * good programming practice. */ public class Complex { // private class variables private double realpart; private double imagpart; // default constructor, real and imaginary parts are initialised to zero. public Complex() { realpart = 0; imagpart = 0; return; } // another constructor public Complex(double x, double y) { realpart = x; imagpart = y; return; } // method to find out value of real part public double getReal() { return realpart; } // method to find out value of imaginary part public double getImag() { return imagpart; } // method to add complex "z" onto this object public void increaseBy(Complex z) { realpart += z.getReal(); imagpart += z.getImag(); return; } // method to add together two complex numbers and return the result public static Complex add(Complex z, Complex w) { Complex sum = new Complex(); sum.realpart = z.getReal() + w.getReal(); sum.imagpart = z.getImag() + w.getImag(); return sum; } // method to print out in usual complex number form public void print() { System.out.print(realpart); if (imagpart < 0) { System.out.print(" - " + (-1*imagpart) + "i"); } else if (imagpart > 0) { System.out.print(" + " + imagpart + "i"); } System.out.println(""); return; } }